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.
Abort
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:
- The calling thread will issue an
Abort
but block here until the finally block is exited i.e. it stops here and does not immediately proceed to the Join
statement.
- The callee thread has its state set to
AbortRequested
.
- The callee continues sleeping.
- When the callee wakes up, as it has a state of
AbortRequested
it will continue executing the finally block code and then "evaporate" i.e. exit.
- When the aborted thread leaves the finally block: no exception is raised, no code after the finally block is executed, and the thread's state is
Aborted
.
- The calling thread is unblocked, continues to the
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.
Interrupt
In the interrupt case if the sleep was not infinite:
Not so well documented...
- The calling thread will issue an
Interrupt
and continue executing.
- The calling thread will block on the
Join
statement.
- The callee thread has its state set to raise an exception on the next blocking call, but crucially as it is in a finally block it is not unblocked i.e. woken.
- The callee continues sleeping.
- When the callee wakes up, it will continue executing the finally block.
- When the interrupted thread leaves the finally block it will throw a
ThreadInterruptedException
on its next blocking call (see code example below).
- The calling thread "joins" and continues as the called thread has exited, however, the unhandled
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.
Summary
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
}
}
Interrupt()
as a mechanism for signalling between threads. There are much more predictable APIs -Monitor
,{Manual|Auto}ResetEvent
, etc – PeeInterupt
. The question is aboutInterupt
, notAbort
. I'm guessing the two things are related (the behaviour would definitely suggest this) but I kind find any docs. – Disintegrate