473,766 Members | 2,159 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

tcpLisetener + Thread problem

Hello there,

Lets say I have something like this in my Mother Of All Threads:

Thread thread1 = new Thread(new ThreadStart(thi s.run));
thread1.Start() ;
//some unimportant code
thread1.Abort() ;
thread1.Join();

And in thread1 I have:

try {
tcpListener = new TcpListener(thi s.port);
tcpListener.Sta rt();
tcpClient = tcpListener.Acc eptTcpClient();
//more unimportant code
} catch (ThreadAbortExc eption) {
tcpClient.Stop( );
//not sure whether I need the line above, but that's not the problem
anyway
tcpListener.Sto p();
}

What happens now is thread1 gets started, gets to the
"tcpListener.Ac ceptTcpClient() " call and waits for a client to connect.
In
the mean time Mother Of All Threads gets to the "thread1.Abort( )" and
raises the ThreadAbortExce ption... and nothing happens. tcpListener
still
hangs and waits for the connection, and blocks the ThreadAbortExce ption
from occuring! Now, shouldn't that be impossible? I was taught to firmly
believe in the Almighty Exception... something's very wrong here...
would
somebody enlighten me, please! :-)

BTW, yes, I know, I could make a socket which will connect to the server
and unblock the Listener, but that's a dirty and ugly hack. There should
be some elegant solution for interupting tcpListener... shouldn't it?

--
"Stara boljka se leci starim lekom...
Dabome vinom, ta nebi valjda mlekom?"
Nov 16 '05 #1
10 10377
The tcp listener calls accept on a socket object which in turn calls out to
a native method using P/Invoke.

I would imagine that the exception don't travel to the native method and
therefore the thread wont be aborted. I've experienced similar behaviour
with SqlDataAdapter. Fill but never found the solution..

--
Patrik Löwendahl [C# MVP]
www.cshrp.net - "Elegant code by witty programmers"
"Nikola Skoric" <ni*******@net4 u.hr> wrote in message
news:MPG.1bd388 43429e2d1989950 @localhost...
Hello there,

Lets say I have something like this in my Mother Of All Threads:

Thread thread1 = new Thread(new ThreadStart(thi s.run));
thread1.Start() ;
//some unimportant code
thread1.Abort() ;
thread1.Join();

And in thread1 I have:

try {
tcpListener = new TcpListener(thi s.port);
tcpListener.Sta rt();
tcpClient = tcpListener.Acc eptTcpClient();
//more unimportant code
} catch (ThreadAbortExc eption) {
tcpClient.Stop( );
//not sure whether I need the line above, but that's not the problem
anyway
tcpListener.Sto p();
}

What happens now is thread1 gets started, gets to the
"tcpListener.Ac ceptTcpClient() " call and waits for a client to connect.
In
the mean time Mother Of All Threads gets to the "thread1.Abort( )" and
raises the ThreadAbortExce ption... and nothing happens. tcpListener
still
hangs and waits for the connection, and blocks the ThreadAbortExce ption
from occuring! Now, shouldn't that be impossible? I was taught to firmly
believe in the Almighty Exception... something's very wrong here...
would
somebody enlighten me, please! :-)

BTW, yes, I know, I could make a socket which will connect to the server
and unblock the Listener, but that's a dirty and ugly hack. There should
be some elegant solution for interupting tcpListener... shouldn't it?

--
"Stara boljka se leci starim lekom...
Dabome vinom, ta nebi valjda mlekom?"

Nov 16 '05 #2
I've dug around for a bit.

There's a stop method on the TcpListener class. The stop method closes and
throws away the underlying socket. Try calling Stop on the listener instead
of abort the thread.

Another way is to kill the thread is to use the API TerminateThread but that
is a potential catastrophy since you wouldn't know what resources the native
code has opened and won't have the chance to close or release.

The third solution is probably a total overkill, you could let the thread
run in a separate appdomain and unload the appdomin itself, this might
terminate the thread but you have no guarantee.

--
Patrik Löwendahl [C# MVP]
www.cshrp.net - "Elegant code by witty programmers"

"Nikola Skoric" <ni*******@net4 u.hr> wrote in message
news:MPG.1bd388 43429e2d1989950 @localhost...
Hello there,

Lets say I have something like this in my Mother Of All Threads:

Thread thread1 = new Thread(new ThreadStart(thi s.run));
thread1.Start() ;
//some unimportant code
thread1.Abort() ;
thread1.Join();

And in thread1 I have:

try {
tcpListener = new TcpListener(thi s.port);
tcpListener.Sta rt();
tcpClient = tcpListener.Acc eptTcpClient();
//more unimportant code
} catch (ThreadAbortExc eption) {
tcpClient.Stop( );
//not sure whether I need the line above, but that's not the problem
anyway
tcpListener.Sto p();
}

What happens now is thread1 gets started, gets to the
"tcpListener.Ac ceptTcpClient() " call and waits for a client to connect.
In
the mean time Mother Of All Threads gets to the "thread1.Abort( )" and
raises the ThreadAbortExce ption... and nothing happens. tcpListener
still
hangs and waits for the connection, and blocks the ThreadAbortExce ption
from occuring! Now, shouldn't that be impossible? I was taught to firmly
believe in the Almighty Exception... something's very wrong here...
would
somebody enlighten me, please! :-)

BTW, yes, I know, I could make a socket which will connect to the server
and unblock the Listener, but that's a dirty and ugly hack. There should
be some elegant solution for interupting tcpListener... shouldn't it?

--
"Stara boljka se leci starim lekom...
Dabome vinom, ta nebi valjda mlekom?"

Nov 16 '05 #3
"Nikola Skoric" <ni*******@net4 u.hr> wrote in message
news:MPG.1bd388 43429e2d1989950 @localhost...
Hello there,

Lets say I have something like this in my Mother Of All Threads:

Thread thread1 = new Thread(new ThreadStart(thi s.run));
thread1.Start() ;
//some unimportant code
thread1.Abort() ;
thread1.Join();

And in thread1 I have:

try {
tcpListener = new TcpListener(thi s.port);
tcpListener.Sta rt();
tcpClient = tcpListener.Acc eptTcpClient();
//more unimportant code
} catch (ThreadAbortExc eption) {
tcpClient.Stop( );
//not sure whether I need the line above, but that's not the problem
anyway
tcpListener.Sto p();
}

What happens now is thread1 gets started, gets to the
"tcpListener.Ac ceptTcpClient() " call and waits for a client to connect.
In
the mean time Mother Of All Threads gets to the "thread1.Abort( )" and
raises the ThreadAbortExce ption... and nothing happens. tcpListener
still
hangs and waits for the connection, and blocks the ThreadAbortExce ption
from occuring! Now, shouldn't that be impossible? I was taught to firmly
believe in the Almighty Exception... something's very wrong here...
would
somebody enlighten me, please! :-)

BTW, yes, I know, I could make a socket which will connect to the server
and unblock the Listener, but that's a dirty and ugly hack. There should
be some elegant solution for interupting tcpListener... shouldn't it?


I don't know why the ThreadAbortExce ption doesn't work (though maybe it's
related to the problem discussed in
news:Ou******** ******@TK2MSFTN GP12.phx.gbl), but the method I use to abort
the TcpListener is to call tcpListener.Sto p() from the main thread (i.e.
from your Mother Of All Threads). This raises a SocketException in the
listening thread (your thread1). I'm not sure whether this is 100% safe,
since calling a method of the TcpListener from a different thread than the
one it was created on may lead to some nasty race condition - but AFAIK it's
never gone wrong in practice.

Chris Jobson
Nov 16 '05 #4
Dana Sun, 10 Oct 2004 18:56:55 +0200
Nikola Skoric (ni*******@net4 u.hr) kaze...
Hello there,

Lets say I have something like this in my Mother Of All Threads: /snip would
somebody enlighten me, please! :-)


Ahhhhhhhhhhhhhh ! Found the soution (although I still lack the
explanation of Exception blocking "feature"). I just put this:

while (!tcpListener.P ending()) Thread.Sleep(50 0);

before this:

tcpClient = tcpListener.Acc eptTcpClient();

Now the Exception is handled and everthing goes fine.

--
"Stara boljka se leci starim lekom...
Dabome vinom, ta nebi valjda mlekom?"
Nov 16 '05 #5
> while (!tcpListener.P ending()) Thread.Sleep(50 0);

Hi Nikola. This is not a great solution for a couple reasons. One is that
clients will have to wait 0-500ms to connect, so your forcing an artificial
connect slowdown. Second, your introducing a spin for no reason. When not
clients connect, your spinning forever which wastes cpu time and on a laptop
or other small device would drain the battery as it would not allow cpu to
go into low power state. Below is simple server implementation that allows
you to block until connect and also allows you to shutdown. You still throw
a socket exception when stopping the listener as it is in blocking mode, but
that is ok as we expect it and catch it before shutting down.

/// <summary>
/// Server listens and writes files to disk.
/// </summary>
public sealed class SimpleServer
{

private readonly Thread thread;
private readonly TcpListener listener;
private bool stopped = true;
private readonly object syncRoot;

public SimpleServer(IP Address listenIP, int port)
{
if ( listenIP == null )
throw new ArgumentNullExc eption();
syncRoot = new object();
listener = new TcpListener(lis tenIP, port);
thread = new Thread(new ThreadStart(Ser verStart));
thread.Name = "Listener";
}

public bool IsStopped
{
get
{
lock(syncRoot)
{
return stopped;
}
}
}

public bool IsStarted
{
get
{
lock(syncRoot)
{
return ! stopped;
}
}
}

public void Start()
{
lock(syncRoot)
{
if ( stopped )
{
stopped = false;
thread.Start();
}
}
}

public void Stop()
{
lock(syncRoot)
{
if ( stopped )
return;
stopped = true;
listener.Stop() ;
}
}

private void ServerStart()
{
try
{
listener.Start( );
Console.WriteLi ne("Listing on: "+listener.Loca lEndpoint.ToStr ing());
while( IsStarted )
{
// Wait for a client to connect.
Console.WriteLi ne("Waiting for a client to connect.");
Socket socket = listener.Accept Socket();
if ( IsStopped )
break;
Console.WriteLi ne("Client Connected: " +
socket.RemoteEn dPoint.ToString ());

// Create and start client worker.
ClientWorker cw = new ClientWorker(so cket);
cw.Start(); // Starts the worker which also starts it's thread.
}
}
catch(SocketExc eption se)
{
// Calling listen.Stop() while Listening will throw
// "A blocking operation was interrupted by a call to
WSACancelBlocki ngCall".
Console.WriteLi ne("Server Socket Exception: " + se.Message);
}
catch(Exception ex)
{
Console.WriteLi ne("Server Exception: " + ex.Message);
}
finally
{
try
{
Stop();
Console.WriteLi ne("Server Stopped.");
}
catch
{
}
}
}
}

Nov 16 '05 #6
Dana Sun, 10 Oct 2004 19:43:58 -0400
William Stacey [MVP] (st***********@ mvps.org) kaze...
while (!tcpListener.P ending()) Thread.Sleep(50 0);
Hi Nikola. This is not a great solution for a couple reasons. One is that
clients will have to wait 0-500ms to connect, so your forcing an artificial
connect slowdown. Second, your introducing a spin for no reason. When not
clients connect, your spinning forever which wastes cpu time and on a laptop
or other small device would drain the battery as it would not allow cpu to
go into low power state. Below is simple server implementation that allows
you to block until connect and also allows you to shutdown. You still throw
a socket exception when stopping the listener as it is in blocking mode, but
that is ok as we expect it and catch it before shutting down.


Thank you for explanation. It is most kind of you. I read this code and
it introduced a number of nice tricks I'll use. Somehow I thought I
shouldn't access objects instanced inside of some other thread... but I
don't remember anyone mentioning that explicitly... just my imagination
then :-)
public bool IsStopped
{
get
{
lock(syncRoot)
{
return stopped;
}
}
}
Say, why not "lock(stopped)" ? Why do you need syncRoot?
public sealed class SimpleServer


And, why sealing the class? Is it you just have a practise of sealing
everthing you can (now, why would you do that?) or do you have a reason
you sealed this one?

Thank you again, you gave me some nice ideas.

--
"Stara boljka se leci starim lekom...
Dabome vinom, ta nebi valjda mlekom?"
Nov 16 '05 #7
Nikola Skoric <ni*******@net4 u.hr> wrote:
Thank you for explanation. It is most kind of you. I read this code and
it introduced a number of nice tricks I'll use. Somehow I thought I
shouldn't access objects instanced inside of some other thread... but I
don't remember anyone mentioning that explicitly... just my imagination
then :-)
public bool IsStopped
{
get
{
lock(syncRoot)
{
return stopped;
}
}
}


Say, why not "lock(stopped)" ? Why do you need syncRoot?


Because stopped is a boolean. Value types don't have associated
monitors.
public sealed class SimpleServer


And, why sealing the class? Is it you just have a practise of sealing
everthing you can (now, why would you do that?) or do you have a reason
you sealed this one?


Sealing classes that aren't specifically designed to be derived from is
good practice, IMO.

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 16 '05 #8
Dana Mon, 11 Oct 2004 09:23:20 +0100
Jon Skeet [C# MVP] (sk***@pobox.co m) kaze...
Nikola Skoric <ni*******@net4 u.hr> wrote:

/snip
Say, why not "lock(stopped)" ? Why do you need syncRoot?


Because stopped is a boolean. Value types don't have associated
monitors.


Thanks!

--
"Stara boljka se leci starim lekom...
Dabome vinom, ta nebi valjda mlekom?"
Nov 16 '05 #9
On Sun, 10 Oct 2004 19:43:58 -0400, William Stacey [MVP] wrote:
Socket socket = listener.Accept Socket();
if ( IsStopped )
break;


Problem here is that if there's no client and no blocking timeout, the
server keeps listening for an indefinite amount of time. So is this really
a solution?

Also, since the thread isn't a background thread (Thread.IsBackg round),
this application, as is, won't terminate on its own under certain
conditions.
Nov 16 '05 #10

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

Similar topics

0
375
by: Steven Brown | last post by:
I'm trying to figure out how to safely use .NET events/delegates in a thread-safe class. There are a couple problems. One is that the standard "if(EventName != null) EventName(...);" call can fail if the event is emptied of all methods between the two statements, implying that some sort of synchronization between this and removals from EventName is needed. The other problem is that if an event with a set of delegates is in the process...
6
2327
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
2705
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
3032
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...
4
6206
by: Madhu Gopinathan | last post by:
Hi All, I am faced with a horrible hang problem. I have a COM exe server that executes some tasks. The task execution manager is a thread that manages the pool of threads, which is 4 per processor. Each task is processed in a separate thread. Each of the executer threads is an STA thread, and it goes ahead and executes the task. No problems are encountered when tasks are executed one at a time, but when multiple tasks are executed...
0
2060
by: Shoveler | last post by:
I've got an odd problem here that I've been beating my head on for days. I've written a class that uses a pre-established connection for communication, meaning I can use this class for a server or a client. After receiving a Socket that has been connected to a RemoteEP, it begins 2 threads by calling out Begin(). My Send Thread pauses until the class Parent wants to send data. Receive Thread keeps checking for incoming data. My...
0
1175
by: David | last post by:
I've written a small windows service, and I'm having a problem that I'm spending a lot more time on than I'd like. If anyone has experienced this problem and has any hints or solutions; they would be appreciated. Simply leaving the threadMain() method if something unexpected occurs during thread execution leaves the thread in a ThreadState.Running state. This (apparently??) causes the Thread.Join() in service.OnStop() to hang...
14
2942
by: Christian Kaiser | last post by:
We have a component that has no window. Well, no window in managed code - it uses a DLL which itself uses a window, and this is our problem! When the garbage collector runs and removes our component (created dynamically by, say, a button click, and then not referenced any more), the GC runs in a different thread, which prohibits the DLL to destroy its window, resulting in a GPF when the WndProc of that window is called - the code is gone...
10
2549
by: Bryce Calhoun | last post by:
Hello, First of all, this is a .NET 1.1 component I'm creating. SUMMARY ----------------------- This component that I'm creating is, for all intents and purposes, a document parser (I'm actually deserializing a SOAP document into an object and parsing out the fields, but that's fairly immaterial to this
0
9571
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10009
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9959
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9838
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...
1
7381
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
5279
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
5423
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3532
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2806
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.