.NET 终结器有超时吗?

发布于 2025-01-16 09:22:25 字数 468 浏览 3 评论 0原文

编辑 - 根据答案重命名为终结器

我正在尝试在终结器中执行一些操作,但程序在完成之前终止。为了模拟,我做了以下测试,最多打印 20

这是否意味着 .NET 终结器在 2 秒后“超时”?

~MyClass()
{
    // do some cleaup
    int i = 0;
    while (true)
    {
        Console.WriteLine(i++);
        Thread.Sleep(100);
    }
}

对于上下文,我有一些后台线程(任务对象),我想优雅地终止它们。我只是测试一下从终结器完成它需要多长时间。

有什么更好的设计模式可以做到这一点?也许有一个“关闭”方法,我必须确保在关闭表单时调用该方法?我知道终结器是为了清理非托管内存,但停止所有线程似乎很好,因为我知道它将被调用。

也许我只是让线程突然终止而不用担心?

Edits - Renamed to finalizer per answer

I am trying to do a few things in a finalizer, and the program terminates before I'm done. To simulate, I made the following test, which prints up to 20

Does this mean .NET finalizer "timeout" after 2 seconds?

~MyClass()
{
    // do some cleaup
    int i = 0;
    while (true)
    {
        Console.WriteLine(i++);
        Thread.Sleep(100);
    }
}

For context, I have some background threads (Task objects) that's I'd like to terminate gracefully. I'm just testing to see how long it takes to do it from the finalizer.

What's a better design pattern for doing this? Perhaps have a "Shutdown" method that I have to make sure is called when closing a form? I know finalizers are meant for cleanup of unmanaged memory, but it seems nice to stop all my threads since I know it will be called.

Maybe I just let the threads terminate abruptly and not worry about it?

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

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

发布评论

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

评论(1

柒夜笙歌凉 2025-01-23 09:22:27

首先,我应该注意到“析构函数”现在更常被称为“终结器”,因为前一个术语意味着这些特殊方法像 C++ 中的析构函数一样工作,但实际上并非如此。因此,如果您使用较新的术语,搜索的运气可能会更好。

对于你的问题,是的,有证据表明.NET有一个关闭期间终结器的时间限制 - 常见的说法是一个终结器花费超过 2 秒,或所有终结器花费 40 秒 - 将导致运行时放弃并只是关闭而不继续让终结器运行 跑步。

我建议研究实现 IDisposable 来确定性地处理清理。 C# 具有语法糖 - using 语句 - 可以帮助消费者更轻松地完成此操作。

First, I should note that "destructors" are now more commonly referred to as "finalizers", as the former term implies these special methods work like destructors in C++, but they really don't. So you might have better luck searching if you use the newer term.

To your question, yes, there is evidence that .NET has a time limit on finalizers during shutdown - common quotes say one finalizer taking more than 2 seconds, or all finalizers taking 40 seconds - will cause the runtime to give up and just shutdown without continuing to let finalizers run.

I would recommend looking into implementing IDisposable to handle cleanup deterministically. C# has syntax sugar - the using statement - to help make this easier on the consumer's side.

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