C# 控制台应用程序不调用 Final 块

发布于 2024-11-26 06:26:16 字数 625 浏览 0 评论 0原文

我正在编写一个控制台应用程序作为计划任务运行,当您使用关闭按钮关闭它时,它似乎不会执行正在运行的代码的finally 块。我尝试使用以下非常简单的控制台应用程序来复制此行为:

using System;
using System.Threading;

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

通过调试器运行时,不会遇到 Console.WriteLine 行上的断点。我不确定这个简单的测试是否按预期工作,或者为什么finally 块似乎没有在此测试或我的生产代码中运行。

我认为finally块总是运行(这不是它们的全部意义吗?)。这是怎么回事?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

无所的.畏惧 2024-12-03 06:26:17

finally 块将始终运行,除非进程本身突然终止 - 这就是这里发生的情况。这不像 Thread.Sleep 抛出异常,并且堆栈正在优雅地展开 - 整个过程只是被中止。至少据我所知:)

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

自控 2024-12-03 06:26:17

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文