Can ThreadAbortException skip finally?

后端 未结 3 946
花落未央
花落未央 2020-12-11 06:43

Everything I\'ve read claims an abort on a thread will execute the finally block before ending from a ThreadAbortException. I wanted to confirm this so I can plan on how to

3条回答
  •  情歌与酒
    2020-12-11 07:39

    The finally block in the worker thread function is executed on the worker thread which is parallel to the main thread. It's a race condition. You can not tell which of worker thread finally or main thread code after abort call get executed sooner. If you need a synchronous abort then you have to put something like that:

            if (testThread.IsAlive)
            {
                testThread.Abort();
    
                bool blnFinishedAfterAbort = testThread.Join(TimeSpan.FromMilliseconds(1000));
                if (!blnFinishedAfterAbort)
                {
                    Console.WriteLine("Thread abort failed.");
                }
            }
            Console.WriteLine("main thread after abort call " + DateTime.Now.ToShortTimeString());
    

    Keep in mind that if you have legacy exception handling enabled (see http://msdn.microsoft.com/en-us/library/ms228965.aspx) and you specified the AppDomain_UnahandledException event handler then the ThreadAbortException will lead execution to that handler BEFORE the finally block in the worker thread function. This is just another example of frustrating and unexpected execution order one should be aware of while aborting threads.

提交回复
热议问题