我为我的代码使用默认的 IDisposable 实现模板(模式)。
片段:
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool isDisposing)
{
if (!this.disposed)
{
if (isDisposing)
{
//cleanup managed resources
}
//cleanup unmanaged resources
this.disposed = true;
}
}
我的问题:为什么在 Dispose 公共方法中调用“GC.SuppressFinalize(this)”?在处置托管资源后,我会将“GC.SuppressFinalize(this)”放在受保护方法的“if (isDisposing)”部分中。
像这样:
protected virtual void Dispose(bool isDisposing)
{
if (!this.disposed)
{
if (isDisposing)
{
//cleanup managed resources
GC.SuppressFinalize(this);
}
//cleanup unmanaged resources
this.disposed = true;
}
}