C#中带有Dispose()的终结器
问题描述:
请参阅MSDN中的代码示例:( http://msdn.microsoft.com/zh-cn/library/b1yfkh5e(v=VS.100).aspx )
See the code sample from MSDN: (http://msdn.microsoft.com/en-us/library/b1yfkh5e(v=VS.100).aspx)
// Design pattern for a base class.
public class Base: IDisposable
{
private bool disposed = false;
//Implement IDisposable.
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
// Free other state (managed objects).
}
// Free your own state (unmanaged objects).
// Set large fields to null.
disposed = true;
}
}
// Use C# destructor syntax for finalization code.
~Base()
{
// Simply call Dispose(false).
Dispose (false);
}
}
在Dispose()实现中,它调用GC.SupressFinalize
In the Dispose() implementation it calls GC.SupressFinalize();, but provide a destructor to finalise the object.
在调用GC.SuppressFinalize()时为析构函数提供实现的意义是什么?
What is the point of providing an implementation for the destructor when GC.SuppressFinalize() is called?
只是有点混淆了意图是什么?
Just little bit confused what the intentions are?
答
有2个情况:
- 您的代码调用Dispose(首选),并且终结器被取消,从而消除了开销。
- 您的代码泄漏了对象,GC调用了终结器。