473,837 Members | 1,460 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Thread Problem

JC
Hi People,

Please I need your help.

This code run a thread ok but Not close later.

thanks...

private void RunServer(int aPortNumber)
{
_listener = new TcpListener(IPA ddress.Any, aPortNumber);
_listener.Start ();

_ServerThread = new Thread(delegate ()
{
AcceptClients() ;
}
);
_ServerThread.S tart();
}

public void Close()
{

_ThreadRun = false;

}
public void AcceptClients()
{
while (_ThreadRun)
using (TcpClient client = _listener.Accep tTcpClient())
{
if (client.Connect ed)
{
NetworkStream stream = client.GetStrea m();
byte[] data = new byte[1024];
stream.Read(dat a, 0, data.Length);
string request = Encoding.ASCII. GetString(data) ;

......
}

}
Nov 29 '06 #1
25 3019
Hi JC,

I might be overlooking this but, how is the Close() method called? Is
that really an event method for a form closing or is it something else?
On Nov 29, 12:39 pm, "JC" <j...@macomexpr ess.comwrote:
Hi People,

Please I need your help.

This code run a thread ok but Not close later.

thanks...

private void RunServer(int aPortNumber)
{
_listener = new TcpListener(IPA ddress.Any, aPortNumber);
_listener.Start ();

_ServerThread = new Thread(delegate ()
{
AcceptClients() ;
}
);
_ServerThread.S tart();
}

public void Close()
{

_ThreadRun = false;

}

public void AcceptClients()
{
while (_ThreadRun)
using (TcpClient client = _listener.Accep tTcpClient())
{
if (client.Connect ed)
{
NetworkStream stream = client.GetStrea m();
byte[] data = new byte[1024];
stream.Read(dat a, 0, data.Length);
string request = Encoding.ASCII. GetString(data) ;

......
}

}
Nov 29 '06 #2
Hi,

That is because _listener.Accep tTcpClient() is blocking the thread. Setting
_ThreadRun to false isn't going to do anything until
_listener.Accep tTcpClient() returns.

Since there doesn't seem to be any error handling code in place, you won't
be able to end the background thread gracefully. Calling _listener.Stop( )
will close the listener, causing AcceptTcpClient to stop blocking, however
an exception will be thrown. Setting _ThreadRun would be pointless in that
case, although it's possible that setting _ThreadRun may cause the loop to
exit if it's set after _listener.Accep tTcpClient() returns and before the
loop restarts, but you shouldn't count on that.

Try the following code instead:

while (true)
{
try
{
using (TcpClient client = _listener.Accep tTcpClient())
{
if (client.Connect ed)
{
NetworkStream stream = client.GetStrea m();
byte[] data = new byte[1024];
stream.Read(dat a, 0, data.Length);
string request = Encoding.ASCII. GetString(data) ;
}
}
}
catch (SocketExceptio n ex)
{
if (ex.SocketError Code == SocketError.Int errupted)
return;
else
throw;
}
}

--
Dave Sexton

"JC" <jc***@macomexp ress.comwrote in message
news:eb******** ******@TK2MSFTN GP02.phx.gbl...
Hi People,

Please I need your help.

This code run a thread ok but Not close later.

thanks...

private void RunServer(int aPortNumber)
{
_listener = new TcpListener(IPA ddress.Any, aPortNumber);
_listener.Start ();

_ServerThread = new Thread(delegate ()
{
AcceptClients() ;
}
);
_ServerThread.S tart();
}

public void Close()
{

_ThreadRun = false;

}
public void AcceptClients()
{
while (_ThreadRun)
using (TcpClient client = _listener.Accep tTcpClient())
{
if (client.Connect ed)
{
NetworkStream stream = client.GetStrea m();
byte[] data = new byte[1024];
stream.Read(dat a, 0, data.Length);
string request = Encoding.ASCII. GetString(data) ;

......
}

}

Nov 29 '06 #3
hi,

I've always learned that relying on exception as a normal process is bad
practice when there is another way to go. And in this case, there is another
way to go : BeginAcceptTcpC lient(...) Just call
_listener.Begin AcceptTcpClient (...) and everything will be fine... ;) if
you need help using it, go there :

http://msdn2.microsoft.com/en-us/lib...tcpclient.aspx

I hope it helps

ThunderMusic

"Dave Sexton" <dave@jwa[remove.this]online.comwrote in message
news:uC******** ********@TK2MSF TNGP06.phx.gbl. ..
Hi,

That is because _listener.Accep tTcpClient() is blocking the thread.
Setting _ThreadRun to false isn't going to do anything until
_listener.Accep tTcpClient() returns.

Since there doesn't seem to be any error handling code in place, you won't
be able to end the background thread gracefully. Calling _listener.Stop( )
will close the listener, causing AcceptTcpClient to stop blocking, however
an exception will be thrown. Setting _ThreadRun would be pointless in
that case, although it's possible that setting _ThreadRun may cause the
loop to exit if it's set after _listener.Accep tTcpClient() returns and
before the loop restarts, but you shouldn't count on that.

Try the following code instead:

while (true)
{
try
{
using (TcpClient client = _listener.Accep tTcpClient())
{
if (client.Connect ed)
{
NetworkStream stream = client.GetStrea m();
byte[] data = new byte[1024];
stream.Read(dat a, 0, data.Length);
string request = Encoding.ASCII. GetString(data) ;
}
}
}
catch (SocketExceptio n ex)
{
if (ex.SocketError Code == SocketError.Int errupted)
return;
else
throw;
}
}

--
Dave Sexton

"JC" <jc***@macomexp ress.comwrote in message
news:eb******** ******@TK2MSFTN GP02.phx.gbl...
>Hi People,

Please I need your help.

This code run a thread ok but Not close later.

thanks...

private void RunServer(int aPortNumber)
{
_listener = new TcpListener(IPA ddress.Any, aPortNumber);
_listener.Start ();

_ServerThread = new Thread(delegate ()
{
AcceptClients() ;
}
);
_ServerThread.S tart();
}

public void Close()
{

_ThreadRun = false;

}
public void AcceptClients()
{
while (_ThreadRun)
using (TcpClient client = _listener.Accep tTcpClient())
{
if (client.Connect ed)
{
NetworkStream stream = client.GetStrea m();
byte[] data = new byte[1024];
stream.Read(dat a, 0, data.Length);
string request = Encoding.ASCII. GetString(data) ;

......
}

}


Nov 29 '06 #4
Hi,
I've always learned that relying on exception as a normal process is bad
practice when there is another way to go
If the code is going to work reliably then exception handling is a must, so
there is no harm in simply returning in the case of an exception that can be
handled.
And in this case, there is another way to go : BeginAcceptTcpC lient(...)
Just call _listener.Begin AcceptTcpClient (...) and everything will be
fine... ;)
<snip>

BeginAcceptTcpC lient will not help here.

The loop still has to block somehow, and if you call _listener.Stop( ) an
exception will still be thrown even though Begin* is called.

IAsyncResult result = _listener.Begin AcceptTcpClient (null, null);

// now, we're just blocking here instead of there ^
using (TcpClient client = _listener.EndAc ceptTcpClient(r esult))
{
...
}

You could have a sub-loop that checks an EventWaitHandle and a variable such
as _ThreadRun, as in the OP, but the code will become more complex with no
real gain. And, exception handling code should still be implemented anyway.

--
Dave Sexton

Nov 29 '06 #5
JC,

Like Dave said TcpListener.Acc eptTcpClient is your biggest problem.
But, even if you fix that the subtle memory barrier problem with
_ThreadRun still exists. You should wrap reads and writes to
_ThreadRun with a lock to ensure changes to it are visible in all
threads.

Brian

JC wrote:
Hi People,

Please I need your help.

This code run a thread ok but Not close later.

thanks...

private void RunServer(int aPortNumber)
{
_listener = new TcpListener(IPA ddress.Any, aPortNumber);
_listener.Start ();

_ServerThread = new Thread(delegate ()
{
AcceptClients() ;
}
);
_ServerThread.S tart();
}

public void Close()
{

_ThreadRun = false;

}
public void AcceptClients()
{
while (_ThreadRun)
using (TcpClient client = _listener.Accep tTcpClient())
{
if (client.Connect ed)
{
NetworkStream stream = client.GetStrea m();
byte[] data = new byte[1024];
stream.Read(dat a, 0, data.Length);
string request = Encoding.ASCII. GetString(data) ;

......
}

}
Nov 29 '06 #6
JC,

Like Dave said TcpListener.Acc eptTcpClient is your biggest problem.
But, even if you fix that the subtle memory barrier problem with
_ThreadRun still exists. You should wrap reads and writes to
_ThreadRun with a lock to ensure changes to it are visible in all
threads.

Brian

JC wrote:
Hi People,

Please I need your help.

This code run a thread ok but Not close later.

thanks...

private void RunServer(int aPortNumber)
{
_listener = new TcpListener(IPA ddress.Any, aPortNumber);
_listener.Start ();

_ServerThread = new Thread(delegate ()
{
AcceptClients() ;
}
);
_ServerThread.S tart();
}

public void Close()
{

_ThreadRun = false;

}
public void AcceptClients()
{
while (_ThreadRun)
using (TcpClient client = _listener.Accep tTcpClient())
{
if (client.Connect ed)
{
NetworkStream stream = client.GetStrea m();
byte[] data = new byte[1024];
stream.Read(dat a, 0, data.Length);
string request = Encoding.ASCII. GetString(data) ;

......
}

}
Nov 29 '06 #7
Yo creo que todos tienen razón. También creo que deberían dejar de
escribir en inglés en un newsgroup en castellano.

Gracias.

Brian Gideon escribió:
JC,

Like Dave said TcpListener.Acc eptTcpClient is your biggest problem.
But, even if you fix that the subtle memory barrier problem with
_ThreadRun still exists. You should wrap reads and writes to
_ThreadRun with a lock to ensure changes to it are visible in all
threads.

Brian

JC wrote:
>Hi People,

Please I need your help.

This code run a thread ok but Not close later.

thanks...

private void RunServer(int aPortNumber)
{
_listener = new TcpListener(IPA ddress.Any, aPortNumber);
_listener.Start ();

_ServerThread = new Thread(delegate ()
{
AcceptClients() ;
}
);
_ServerThread.S tart();
}

public void Close()
{

_ThreadRun = false;

}
public void AcceptClients()
{
while (_ThreadRun)
using (TcpClient client = _listener.Accep tTcpClient())
{
if (client.Connect ed)
{
NetworkStream stream = client.GetStrea m();
byte[] data = new byte[1024];
stream.Read(dat a, 0, data.Length);
string request = Encoding.ASCII. GetString(data) ;

......
}

}
Nov 29 '06 #8
Hi Brian,

Good point about volatility, however the variable is pointless anyway. It
won't allow the OP to control the background thread.

The only way to stop the _listener.Accep tTcpClient method from blocking is
to call _listener.Stop( ), which will cause an exception to be thrown and the
variable won't be checked.

BeginAcceptTcpC lient cannot be stopped gracefully either. Calling
_listener.Stop( ) will cause an exception to be thrown as well.

The OP should write code to handle this exception and exit the background
thread, as in my example.

--
Dave Sexton

"Brian Gideon" <br*********@ya hoo.comwrote in message
news:11******** *************@j 44g2000cwa.goog legroups.com...
JC,

Like Dave said TcpListener.Acc eptTcpClient is your biggest problem.
But, even if you fix that the subtle memory barrier problem with
_ThreadRun still exists. You should wrap reads and writes to
_ThreadRun with a lock to ensure changes to it are visible in all
threads.

Brian

JC wrote:
>Hi People,

Please I need your help.

This code run a thread ok but Not close later.

thanks...

private void RunServer(int aPortNumber)
{
_listener = new TcpListener(IPA ddress.Any, aPortNumber);
_listener.Start ();

_ServerThread = new Thread(delegate ()
{
AcceptClients() ;
}
);
_ServerThread.S tart();
}

public void Close()
{

_ThreadRun = false;

}
public void AcceptClients()
{
while (_ThreadRun)
using (TcpClient client = _listener.Accep tTcpClient())
{
if (client.Connect ed)
{
NetworkStream stream = client.GetStrea m();
byte[] data = new byte[1024];
stream.Read(dat a, 0, data.Length);
string request = Encoding.ASCII. GetString(data) ;

......
}

}

Nov 29 '06 #9
yes, exception handling is a must to handle exceptional situations, but the
process should never be based on exception handling as you are advising
here... and yes there is harm because exception handling is very costy
resource-wise, so if you can avoid it, avoid it...

I really think you should read on asynchronous programming, it would really
help... I've done this kind of processing many times using
BeginAcceptTcpC lient(...) without any problem when stopping my apps... I
don't have sample code at hand, but I know it worked fine... follow the
link I provided and you will most likely find what you need...

I hope it helps

ThunderMusic

"Dave Sexton" <dave@jwa[remove.this]online.comwrote in message
news:%2******** **********@TK2M SFTNGP06.phx.gb l...
Hi,
>I've always learned that relying on exception as a normal process is bad
practice when there is another way to go

If the code is going to work reliably then exception handling is a must,
so there is no harm in simply returning in the case of an exception that
can be handled.
>And in this case, there is another way to go : BeginAcceptTcpC lient(...)
Just call _listener.Begin AcceptTcpClient (...) and everything will be
fine... ;)

<snip>

BeginAcceptTcpC lient will not help here.

The loop still has to block somehow, and if you call _listener.Stop( ) an
exception will still be thrown even though Begin* is called.

IAsyncResult result = _listener.Begin AcceptTcpClient (null, null);

// now, we're just blocking here instead of there ^
using (TcpClient client = _listener.EndAc ceptTcpClient(r esult))
{
...
}

You could have a sub-loop that checks an EventWaitHandle and a variable
such as _ThreadRun, as in the OP, but the code will become more complex
with no real gain. And, exception handling code should still be
implemented anyway.

--
Dave Sexton

Nov 29 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
2330
by: Tony Proctor | last post by:
Hi everyone We're experiencing some serious anomalies with the scheduling of ASP threads. I'd be interested to hear if anyone knows what algorithm is used (e.g. simple round-robin, or something more sophisticated), and what situations might perturb it. Even a hint as to what would be considered normal scheduling might help. The root of our problem is that we observed a normally well-behaved web application suddenly limit itself to a...
7
2712
by: Ivan | last post by:
Hi I have following problem: I'm creating two threads who are performing some tasks. When one thread finished I would like to restart her again (e.g. new job). Following example demonstrates that. Problem is that when program is started many threads are created (see output section), when only two should be running at any time. Can you please help me to identify me where the problem is? Best regards
20
3039
by: Doug Thews | last post by:
I ran into an interesting re-pain delay after calling the Abort() method on a thread, but it only happens the very first time I call it. Every time afterward, there is no delay. I've got a delegate inside the UI that I call to update the progress meter. I use the Suspend() and Abort() methods based on button events. I can watch the progress meter increase just fine when the thread is running. When I select Start, I enable the Cancel...
6
23748
by: Tomaz Koritnik | last post by:
I have a class that runs one of it's method in another thread. I use Thread object to do this and inside ThreadMethod I have an infinite loop: While (true) { // do something Thread.Sleep(100); } The problem is that I don't know how to terminate the thread when my class
13
5103
by: Bob Day | last post by:
Using vs2003, vb.net I start a thread, giving it a name before start. Code snippet: 'give each thread a unique name (for later identification) Trunk_Thread.Name = "Trunk_0_Thread" ' allow only 1 thread per line Trunk_Thread.ApartmentState = ApartmentState.STA
4
2566
by: fred | last post by:
I use a Synclock in a secondary thread and also stop the thread using the abort method. If the abort occurs while the thread is in the Synclock will the SyncLock always be released before the thread stops or do I need to add some extra code to avoid Synclock staying on after the thread has been stopped. Thanks Fred
51
54905
by: Hans | last post by:
Hi all, Is there a way that the program that created and started a thread also stops it. (My usage is a time-out). E.g. thread = threading.Thread(target=Loop.testLoop) thread.start() # This thread is expected to finish within a second
14
6893
by: joey.powell | last post by:
I am using VS2005 for a windows forms application. I need to be able to use a worker thread function to offload some processing from the UI thread. The worker thread will need access to a datagridview on the form. I am using the following code to spawn the worker thread... Thread WorkerThread = new Thread(new ThreadStart(WT_MyFunction)); WorkerThread.IsBackground = true; WorkerThread.Start(); The problem I am having is...I cannot seem...
7
5903
by: Sin Jeong-hun | last post by:
Hi. I'm writing a Client/Multi-threaded Server program on Windows Vista. It worked fine on Windows Vista, but when the server ran on Windows XP, I/O operation has been aborted because of either a thread exit or an application request exception randomly occurred at the OnReceive method (asynchronous tcp stream reading). I searched all over the internet and found a post posted few years ago. He had the same problem as me, and he said it
34
2839
by: Creativ | last post by:
Why does Thread class not support IDisposable? It's creating quite some problem. Namely, it can exhaust the resource and you have not control over it.
0
9683
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10882
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10275
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9407
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7811
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7005
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5670
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5851
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3126
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.