I understand that Thread.Abort should raise a ThreadAbortException in a blocked thread, however this does not seem to be the case with TcpListener.AcceptSocket . Here is the most basic illustration of the problem:
class Program { static void Main(string[] args) { Thread thread = new Thread(Listen); thread.Start(); Thread.Sleep(1000);
A call to thread.Abort() should stop AcceptSocket and execute a ThreadAbortException handler. Howerver does not do this.
Switching my Listen AcceptSocket wrapper to ListenAsync, which calls BeginAcceptSocket instead:
static void ListenAsync() { try { ManualResetEvent clientConnected = new ManualResetEvent(false); Console.WriteLine("Starting to listen"); TcpListener listener = new TcpListener(IPAddress.Any, 4070); listener.Start(); clientConnected.Reset(); var iasyncResult = listener.BeginAcceptSocket((ar) => { Socket socket = listener.EndAcceptSocket(ar); Console.WriteLine("Connected!"); clientConnected.Set(); }, null); clientConnected.WaitOne(); return; } catch (ThreadAbortException exception) { Console.WriteLine("Abort requested"); } }
In this case, the "seems" is working fine. A ThreadAbortException is thrown when a thread executes WaitOne. HOWEVER, the thread created by calling BeginAcceptSocket is still working and is able to accept a socket (I checked this by opening this port using Telnet)
Finally, I added Listener.Stop as part of the TheadAbortException handler and tried to catch an EndAcceptSocket call (since the socket is placed by Stop)
Is this really the best approach that starts and stops listening on socket connections?
multithreading c # sockets
Ralph Shillington Apr 25 '11 at 12:21 2011-04-25 12:21
source share