Search code examples
c#.netmultithreadingthread-abortthreadabortexception

Thread.Abort doesn't seem to throw a ThreadAbortException because of AcceptSocket


I am calling ChannelServer.ListeningThread.Abort on the following thread, however nothing seems to happen. I would like to be more specific, but I can't think of anything more. There seems to be no ThreadAbortException that is thrown, and this exception should be thrown regardless of the blocking listener (it works perfectly on threads that are blockingly-receiving).

Important EDIT: With a ManualResetEvent.WaitOne instead of AcceptSocket, as Lyrik has suggested for testing, it works perfectly. How come AcceptSocket blocks the ThreadAbortException?

LINK: This forum thread seems to discuss the same issue, although I cannot figure anything out of it: http://www.tek-tips.com/viewthread.cfm?qid=319436&page=413

ChannelServer.ListeningThread = new Thread(new ThreadStart(delegate()
{
    Log.Inform("Waiting for clients on thread {0}.", Thread.CurrentThread.ManagedThreadId);

    while (true)
    {
        try
        {
            new Thread(new ParameterizedThreadStart(ChannelClientHandler.Initialize)).Start(ChannelServer.Listener.AcceptSocket());
        }
        catch (ThreadAbortException)
        {
            Log.Inform("Aborted client listening thread {0}.", Thread.CurrentThread.ManagedThreadId);
            break;
        }
    }
}));
ChannelServer.ListeningThread.Start();

Solution

  • This works, but it's incredibly sloppy and thread-wasting. Could anyone just point me to a way to throw an exception that "AcceptSocket" won't automatically catch?

    ChannelServer.ListeningThread = new Thread(new ThreadStart(delegate()
    {
        Log.Inform("Waiting for clients on thread {0}.", Thread.CurrentThread.ManagedThreadId);
    
        while (true)
        {
            try
            {
                ChannelServer.ClientConnected.Reset();
                ChannelServer.Listener.BeginAcceptSocket(new AsyncCallback(ChannelClientHandler.EndAcceptSocket), ChannelServer.Listener);
                ChannelServer.ClientConnected.WaitOne();
            }
            catch (ThreadInterruptedException)
            {
                Log.Inform("Interrupted client listening thread {0}.", Thread.CurrentThread.ManagedThreadId);
                break;
            }
        }
    }));
    ChannelServer.ListeningThread.Start();