I have been looking all over MSDN and can’t find a reason why Thread can not be interrupted when sleeping within finally block. I have tried aborting with no success.
Is there any way how to wake up thread when sleeping within finally block?
Thread t = new Thread(ProcessSomething) {IsBackground = false};
t.Start();
Thread.Sleep(500);
t.Interrupt();
t.Join();
private static void ProcessSomething()
{
try { Console.WriteLine("processing"); }
finally
{
try
{
Thread.Sleep(Timeout.Infinite);
}
catch (ThreadInterruptedException ex)
{
Console.WriteLine(ex.Message);
}
}
}
Surprisingly MSDN claims thread CAN be aborted in finally block: http://msdn.microsoft.com/en-us/library/aa332364(v=vs.71).aspx
“There is a chance the thread could abort while a finally block is running, in which case the finally block is aborted.”
edit
I find Hans Passant comment as best answer since this explains why Thread sometimes can and can not be interrupted/aborted in finally block. And that is when process is shutting down.
thanks
Aborting and interrupting threads should be avoided if possible as this can corrupt the state of a running program. For example, imagine you aborted a thread that was holding locks open to resources, these locks would never be released.
Instead consider using a signalling mechanism so that threads can co-operate with each other and so handle blocking and unblocking gracefully, e.g:
Update
Quite an interesting low-level issue. Although
Abort()is documented,Interrupt()is much less so.The short answer to your question is no, you cannot wake a thread in a finally block by calling
AbortorInterrupton it.Not being able to abort or interrupt threads in finally blocks is by design, simply so that finally blocks have a chance to run as you would expect. If you could abort and interrupt threads in finally blocks this could have unintended consequences for cleanup routines, and so leave the application in a corrupted state – not good.
A slight nuance with thread interrupting, is that an interrupt may have been issued against the thread any time before it entered the finally block, but whilst it was not in a
SleepWaitJoinstate (i.e. not blocked). In this instance if there was a blocking call in the finally block it would immediately throw aThreadInterruptedExceptionand crash out of the finally block. Finally block protection prevents this.As well as protection in finally blocks, this extends to try blocks and also CERs (Constrained Execution Region) which can be configured in user code to prevent a range of exceptions being thrown until after a region is executed – very useful for critical blocks of code which must be completed and delay aborts.
The exception (no pun intended) to this are what are called Rude Aborts. These are
ThreadAbortExceptionsraised by the CLR hosting environment itself. These can cause finally and catch blocks to be exited, but not CERs. For example, the CLR may raise Rude Aborts in response to threads which it has judged to be taking too long to do their work\exit e.g. when trying to unload an AppDomain or executing code within the SQL Server CLR. In your particular example, when your application shuts down and the AppDomain unloads, the CLR would issue a Rude Abort on the sleeping thread as there would be an AppDomain unload timeout.Aborting and interrupting in finally blocks is not going to happen in user code, but there is slightly different behavior between the two cases.
Abort
When calling
Aborton a thread in a finally block, the calling thread is blocked. This is documented:In the abort case if the sleep was not infinite:
Abortbut block here until the finally block is exited i.e. it stops here and does not immediately proceed to theJoinstatement.AbortRequested.AbortRequestedit will continue executing the finally block code and then "evaporate" i.e. exit.Aborted.Joinstatement and immediately passes as the called thread has exited.So given your example with an infinite sleep, the calling thread will block forever at step 1.
Interrupt
In the interrupt case if the sleep was not infinite:
Not so well documented…
Interruptand continue executing.Joinstatement.ThreadInterruptedExceptionon its next blocking call (see code example below).ThreadInterruptedExceptionin step 6 has now flattened the process…So again given your example with an infinite sleep, the calling thread will block forever, but at step 2.
Summary
So although
AbortandInterrupthave slightly different behavior, they will both result in the called thread sleeping forever, and the calling thread blocking forever (in your example).Only a Rude Abort can force a blocked thread to exit a finally block, and these can only be raised by the CLR itself (you cannot even use reflection to diddle
ThreadAbortException.ExceptionStateas it makes an internal CLR call to get theAbortReason– no opportunity to be easily evil there…).The CLR prevents user code from causing finally blocks to be prematurely exited for our own good – it helps to prevent corrupted state.
For an example of the slightly different behavior with
Interrupt: