下面是VS提供的Dispose模式:
class DisposeClass : IDisposable
{
private bool disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
// TODO: dispose managed state (managed objects).
}
// TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
disposedValue = true;
}
}
~DisposeClass()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(false);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
我不明白为什么在调用对象的Dispose()方法时需要调用GC.SuppressFinalize()。
例如,让我们删除GC.SuppressFinalize():
public void Dispose()
{
Dispose(true);
}
然后
DisposeClass dc = new DisposeClass();
dc.Dispose();
因为在我们第一次调用Dispose()时,displacedValue将设置为true,然后调用该对象的Finalize方法时,!disposedValue
为false,则不会执行任何操作。那么为什么我们需要致电GC.SuppressFinalize()
?