【发布时间】:2012-04-14 01:30:17
【问题描述】:
析构函数是奇怪的。我试图通过使用“智能”引用管理来消除使用一次性模式的需要,确保垃圾收集器可以在正确的时间收集对象。在我的一个析构函数中,我不得不等待来自另一个对象的事件,我注意到它没有。应用程序简单地关闭,析构函数在执行过程中终止。 我希望总是允许析构函数完成运行,但以下测试表明这不是真的。
using System;
using System.Diagnostics;
using System.Threading;
namespace DestructorTest
{
class Program
{
static void Main( string[] args )
{
new DestructorTest();
new LoopDestructorTest();
using ( new DisposableTest() ) { }
}
}
class DestructorTest
{
~DestructorTest()
{
// This isn't allowed to finish.
Thread.Sleep( 10000 );
}
}
class LoopDestructorTest
{
~LoopDestructorTest()
{
int cur = 0;
for ( int i = 0; i < int.MaxValue; ++i )
{
cur = i;
}
// This isn't allowed to finish.
Debug.WriteLine( cur );
}
}
class DisposableTest : IDisposable
{
public void Dispose()
{
// This of course, is allowed to finish.
Thread.Sleep( 10000 );
}
}
}
那么,析构函数不能保证完成运行吗?
【问题讨论】:
-
在终结器中等待来自另一个对象的事件?这太疯狂了!
-
您确实应该坚持使用
IDisposable模式,以获得可靠的销毁和资源释放。 -
@MattDavey ... 并等待来自另一个对象的事件继续触发
Dispose()不是疯狂吗?有什么区别? -
link阅读
The Finalize method might not run to completion or might not run at all in the following exceptional circumstances:下的第二个项目符号
标签: c# destructor finalizer