Why code in finally block doesn't execute?

Your code is running in a background thread. When you set the AutoResetEvent, your single foreground thread terminates (as you reach the end of the Main method) and the process is torn down "immediately".

In fact, I think it likely that your finally block starts executing, but as the first thing you do is sleep for two seconds, the process quits before it gets to your WriteLine call.

If your Main method were still running, or any other foreground thread were keeping the process alive, you'd see your finally block complete as normal. This isn't really a matter of "finally on other threads" - it's a matter of "the process only stays alive while there are foreground threads".


You can prevent the main method from exiting until the finally has executed. There are many possible approaches.

  • You can use synchronization to achieve this. For example using a ResetEvent, similar to what you are already doing, or creating a thread explicitly and joining with it.

  • You could just a simple sleep or readline at the end of the Main method:

    h.WaitOne();
    Console.ReadLine();
    

Then the user can control when the program exits.

  • You can use a non-background thread instead of a thread from the thread pool. Then the program won't exit until the thread has also terminated. This is probably the best and simpest option if you want your program not to terminate until the thread has completed.