Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 handle some 3rd party code that can hang indefinitely. However the following test has me confused:

public void runTest(DateTime deadline)
{
    testThread = new Thread(() => 
    {
        try 
        {
            Console.WriteLine("test thread started at " + DateTime.Now.ToShortTimeString());
            while (true) { }
        }
        finally
        {
            Console.WriteLine("test thread entered FINALLY at " + DateTime.Now.ToShortTimeString());
            while (true) { }
        }
    });
    testThread.Start();
    while (testThread.IsAlive && deadline.Subtract(DateTime.Now).TotalSeconds > 0)
    {
        Console.WriteLine("main thread while loop " + DateTime.Now.ToShortTimeString());
        Thread.Sleep(10000);
    }
    if (testThread.IsAlive)
        testThread.Abort();
    Console.WriteLine("main thread after abort call " + DateTime.Now.ToShortTimeString());
}

What I find when running this is that console never mentions entering the finally block. The application continues on after the .abort call as if there is no finally block at all. Am I doing something wrong? Shouldn't control pass to the finally block before reaching the final write to console or is the execution order still a function of the fact that the finally is in a separate thread or something?

See Question&Answers more detail:os

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

1 Answer

Docs say: ThreadAbortException is a special exception that can be caught, but it will automatically be raised again at the end of the catch block. When this exception is raised, the runtime executes all the finally blocks before ending the thread. Because the thread can do an unbounded computation in the finally blocks or call Thread.ResetAbort to cancel the abort, there is no guarantee that the thread will ever end.

I'm pretty sure your thread is being dumped because you exit the method and lose a reference to it, and so it gets collected by the Garbage Collector. Try making the testThread variable a field member of the class and see what happens.

That, or you have a race condition since the threads run in parallel: the main thread is finishing before the spun-up test thread can output the finally data (Exceptions are expensive and take time to reach catch or finally blocks).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...