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