Why is thread not interrupted when sleeping in finally block
Asked Answered
H

2

11

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

Hendecahedron answered 15/8, 2011 at 12:19 Comment(6)
I don't know the answer to the question, but I do know that as a general rule I avoid Interrupt() as a mechanism for signalling between threads. There are much more predictable APIs - Monitor, {Manual|Auto}ResetEvent, etcPee
I was more looking for any explanation/documentation when Interrupt/Abort does not work in finally and why is MSDN saying the opposite. My example is more complex type of poller and I am reading it now to waithandles as suggested.Hendecahedron
There are two kind of thread aborts. The friendly one will not interrupt code in a finally block. The unfriendly one is invoked when the process is shutting down on a thread that has IsBackground equal to true or when it is terminating on an unhandled exception. Now it doesn't matter that code got rudely interrupted.Daggett
@Hans Does your comment hold for Thread.Interupt too? The way it behaves does, but couldn't find any documentation.Disintegrate
@chiba - The CLR doesn't use Thread.Interrupt to shutdown threads. The unfriendly kind is a CLR implementation detail.Daggett
@Hans Sorry, slight misunderstanding. I'm not referring to how the CLR shuts down threads, I'm referring to how your comment relates to Interupt. The question is about Interupt, not Abort. I'm guessing the two things are related (the behaviour would definitely suggest this) but I kind find any docs.Disintegrate
D
11

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:

  1. 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.
  2. The callee thread has its state set to AbortRequested.
  3. The callee continues sleeping.
  4. 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.
  5. 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.
  6. 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...

  1. The calling thread will issue an Interrupt and continue executing.
  2. The calling thread will block on the Join statement.
  3. 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.
  4. The callee continues sleeping.
  5. When the callee wakes up, it will continue executing the finally block.
  6. When the interrupted thread leaves the finally block it will throw a ThreadInterruptedException on its next blocking call (see code example below).
  7. 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
    }
}   
Disintegrate answered 15/8, 2011 at 12:44 Comment(0)
N
5

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.

Neutrino answered 15/8, 2011 at 12:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.