Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Console App Not Calling Finally Block

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?

like image 869
Jackson Pope Avatar asked Feb 24 '23 11:02

Jackson Pope


1 Answers

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 :)

like image 189
Jon Skeet Avatar answered Mar 07 '23 17:03

Jon Skeet