4

I'm writing a console app to run as a scheduled task and it doesn't appear to execute the finally block of the running code when you close it using the close button. I've tried to replicate this behaviour with the following very simple console app:

using System;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Thread.Sleep(60000);
            }
            finally
            {
                Console.WriteLine("Finally");
            }
        }
    }
}

When run through the debugger this doesn't hit a breakpoint on the Console.WriteLine line. I'm not sure if this simple test works as intended or why the finally block doesn't appear to run in either this test or my production code.

I thought finally blocks always run (isn't that the whole point of them?). What is going on here?

Jackson Pope
  • 14,520
  • 6
  • 56
  • 80
  • It turns out what I need to do is use the code in this answer: http://stackoverflow.com/questions/474679/capture-console-exit-c/474743#474743 – Jackson Pope Jul 25 '11 at 08:39

2 Answers2

6

A finally block will always run unless the process itself terminates abruptly - which is what's happening here. It's not like Thread.Sleep is throwing an exception, and the stack is unwinding gracefully - the whole process is just being aborted. At least as far as I can tell :)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

It turns out what I needed to do was copy the code from this answer: Capture console exit C#

Community
  • 1
  • 1
Jackson Pope
  • 14,520
  • 6
  • 56
  • 80