我有以下代码:
public void Dispose()
{
if (_instance != null)
{
_instance = null;
// Call GC.SupressFinalize to take this object off the finalization
// queue and prevent finalization code for this object from
// executing a second time.
GC.SuppressFinalize(this);
}
}
虽然有评论解释了那个与 GC 相关的调用的目的,但我仍然不明白为什么它在那里。
一旦所有实例不复存在,对象是否注定要进行垃圾回收,例如在 using
block 中使用时?
这将发挥重要作用的用例场景是什么?
最佳答案
在实现处置模式时,您还可以向调用 Dispose()
的类添加终结器。这是为了确保 Dispose()
总是 被调用,即使客户端忘记调用它。
为了防止 dispose 方法运行两次(如果对象已经被释放),你添加了 GC.SuppressFinalize(this);
。该文档提供了一个 sample :
class MyResource : IDisposable
{
[...]
// This destructor will run only if the Dispose method
// does not get called.
~MyResource()
{
// Do not re-create Dispose clean-up code here.
// Calling Dispose(false) is optimal in terms of
// readability and maintainability.
Dispose(false);
}
// Implement IDisposable.
// Do not make this method virtual.
// A derived class should not be able to override this method.
public void Dispose()
{
Dispose(true);
// This object will be cleaned up by the Dispose method.
// Therefore, you should call GC.SupressFinalize to
// take this object off the finalization queue
// and prevent finalization code for this object
// from executing a second time.
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
// Check to see if Dispose has already been called.
if(!this.disposed)
{
// If disposing equals true, dispose all managed
// and unmanaged resources.
if(disposing)
{
// Dispose managed resources.
component.Dispose();
}
// Call the appropriate methods to clean up
// unmanaged resources here.
resource.Cleanup()
}
disposed = true;
}
}
关于c# - Dispose() 方法中 GC.SuppressFinalize(this) 的目的是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3038571/