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
A thread that is in the sleeping or waiting state can be interrupted with the help of the interrupt() method of Thread class.
Explanation: It releases all the locks it has If a thread goes to sleep. It doesn't open any locks. One important distinction that has yet to be mentioned is that while sleeping, a Thread does not release the locks it holds, whereas waiting releases the lock on the object on which wait() is called.
sleep() blocks the main UI thread [closed] Save this question. Show activity on this post.
Threads can be interrupted, and when a thread is interrupted, it will throw InterruptedException. In the next sections, we'll see InterruptedException in detail and learn how to respond to it.
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:
private readonly AutoResetEvent ProcessEvent = new AutoResetEvent(false);
private readonly AutoResetEvent WakeEvent = new AutoResetEvent(false);
public void Do()
{
Thread th1 = new Thread(ProcessSomething);
th1.IsBackground = false;
th1.Start();
ProcessEvent.WaitOne();
Console.WriteLine("Processing started...");
Thread th2 = new Thread(() => WakeEvent.Set());
th2.Start();
th1.Join();
Console.WriteLine("Joined");
}
private void ProcessSomething()
{
try
{
Console.WriteLine("Processing...");
ProcessEvent.Set();
}
finally
{
WakeEvent.WaitOne();
Console.WriteLine("Woken up...");
}
}
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 Abort
or Interrupt
on 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 SleepWaitJoin
state (i.e. not blocked). In this instance if there was a blocking call in the finally block it would immediately throw a ThreadInterruptedException
and 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 ThreadAbortExceptions
raised 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.
When calling Abort
on a thread in a finally block, the calling thread is blocked. This is documented:
The thread that calls Abort might block if the thread that is being aborted is in a protected region of code, such as a catch block, finally block, or constrained execution region.
In the abort case if the sleep was not infinite:
Abort
but block here until the finally block is exited i.e. it stops here and does not immediately proceed to the Join
statement. AbortRequested
.AbortRequested
it will continue executing the finally block code and then "evaporate" i.e. exit.Aborted
.Join
statement 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.
In the interrupt case if the sleep was not infinite:
Not so well documented...
Interrupt
and continue executing.Join
statement.ThreadInterruptedException
on its next blocking call (see code example below).ThreadInterruptedException
in 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.
So although Abort
and Interrupt
have 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.ExceptionState
as it makes an internal CLR call to get the AbortReason
- 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
:
internal class ThreadInterruptFinally
{
public static void Do()
{
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
{
Thread.Sleep(2 * 1000);
}
Console.WriteLine("Exited finally...");
Thread.Sleep(0); //<-- ThreadInterruptedException
}
}
The whole point of a finally
block is to hold something that will not be affected by an interrupt or abort and will run to normal completion no matter what. Permitting a finally
block to be aborted or interrupted would pretty much defeat the point. Sadly, as you noted, finally
blocks can be aborted or interrupted due to various race conditions. This is why you will see many people advising you not to interrupt or abort threads.
Instead, use cooperative design. If a thread is supposed to be interrupted, instead of calling Sleep
, use a timed wait. Instead of calling Interrupt
signal the thing the thread waits for.
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