简体   繁体   中英

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?

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

事实证明我需要做的是从这个答案中复制代码: Capture console exit C#

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM