析构函数在 C# 中完成任务之前结束?

Destructor ends before completing its task in C#?

desctructorCheck class 中的以下 destructor 代码在将近 2 秒后关闭控制台,然后从用户。

~destructorCheck() {
   Console.WriteLine("Destructor");
   Console.ReadLine( );
}

为什么要关闭? 析构函数 是否有任何计时器来完成其清理过程?

原因是,因为析构函数的调用方式:

引用MSDN:

'The programmer has no control over when the destructor is called because this is determined by the garbage collector. The garbage collector checks for objects that are no longer being used by the application. If it considers an object eligible for destruction, it calls the destructor (if any) and reclaims the memory used to store the object. Destructors are also called when the program exits.'

我同意阅读 Eric Lippert 的博客是一件好事!

如果您需要确保在销毁 C# 对象时发生某些事情,您可能应该实现 IDisposable 并将闭包逻辑放入 Dispose 方法中。

是的。终结器在终止之前有有限的时间 运行。

这是终结器成为最后手段的众多原因之一。他们不能保证首先 运行,也不能保证完成。它们只是 运行ning 因为框架确实需要该对象消失 现在 -- 它要么因为它需要内存而对其进行 GC,要么您的应用程序正在关闭。

我很确定时间限制是 ~2 秒,我不知道有什么办法可以改变它。