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?
A finally block always executes, regardless of whether an exception is thrown.
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.
System. exit() can be used to avoid the execution of the finally block Finally Block.
Yes, it is not mandatory to use catch block with finally.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With