.NET 终结器有超时吗?
编辑 - 根据答案重命名为终结器
我正在尝试在终结器中执行一些操作,但程序在完成之前终止。为了模拟,我做了以下测试,最多打印 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,我应该注意到“析构函数”现在更常被称为“终结器”,因为前一个术语意味着这些特殊方法像 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.