Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does ThreadAbortException still enforce executing the code in finally (try/catch) section?

I have a System.Timers.Timer timer which it's AutoReset is set to false. I use a try/finally to insure I Start the timer at the end of it's callback (I use the timer this way to prevent overlapping of callback execution). Code:

// inside timer call back
try
{
    // Do something
}
finally
{
    timer.Start(); // Is this line always executed?
}

My question is what happens if the executing thread is Aborted? Does the finally section still executed or there's no thread to run that part?

like image 319
Xaqron Avatar asked May 23 '11 15:05

Xaqron


People also ask

Does finally block always execute in C#?

A finally block always executes, regardless of whether an exception is thrown.

Is finally executed before or after catch?

What Is finally? finally defines a block of code we use along with the try keyword. It defines code that's always run after the try and any catch block, before the method is completed. The finally block executes regardless of whether an exception is thrown or caught.

How do you avoid Finally in try catch?

System. exit() can be used to avoid the execution of the finally block Finally Block.

Can finally be written before catch?

Yes, it is not mandatory to use catch block with finally.


1 Answers

The official source...

When a call is made to the Abort method to destroy a thread, the common language runtime throws a ThreadAbortException. 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. If you want to wait until the aborted thread has ended, you can call the Thread.Join method. Join is a blocking call that does not return until the thread actually stops executing.

Read more about it on MSDN.

like image 55
Chris Baxter Avatar answered Sep 23 '22 22:09

Chris Baxter