Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
854 views
in Technique[技术] by (71.8m points)

c# - 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();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I'm not sure why you're getting that error, but here is a simple example that works:

ManualResetEvent mrse = new ManualResetEvent(false);
Thread test = new Thread(() =>
    {
        while (true)
        {
            try
            {
                mrse.WaitOne();
            }
            catch (ThreadAbortException)
            {
                Console.WriteLine("No problem here...");
            }
        }
    });

test.IsBackground = true;
test.Start();

Thread.Sleep(1000);
test.Abort();
Console.ReadKey();

So it works for me... I assumed you've stepped through the debugger and your break point inside the catch statement wasn't hit, is that correct?

Note: it's bad practice to call Abort, instead you should call Interrupt and handle the ThreadInterruptedException... it's much safer.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...