为什么我们需要在下面的代码片段中配置参数。
此外,我们在终结器中使用 false 调用 dispose,它不会释放或进行清理。
那么如果 dispose 永远不会被调用呢?
不是总是在终结器之前调用 dispose 吗?
using System;
public class MyClass : IDisposable
{
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
**//Do we really need this condition?
if (disposing)**
{
// called via myClass.Dispose().
// OK to use any private object references
}
disposed = true;
}
}
public void Dispose()
// Implement IDisposable
{
Dispose(true);
GC.SuppressFinalize(this);
}
~MyClass() // the finalizer
{
//why do we need to call with false?
Dispose(false);
}
}
换句话说,为什么不呢?
using System;
public class MyClass : IDisposable
{
private bool disposed = false;
protected virtual void Dispose(bool suppressFinalize)
{
if (!disposed)
{
//Do we really need this condition?
// called via myClass.Dispose().
// OK to use any private object references
disposed = true;
}
if (!suppressFinalize)
{
GC.SuppressFinalize(this);
}
}
public void Dispose()
// Implement IDisposable
{
Dispose(true);
}
~MyClass() // the finalizer
{
//why do we need to call with false?
Dispose(false);
}
}
事实上,我真的需要终结器吗?为什么不是这个?
using System;
public class MyClass : IDisposable
{
public void Dispose()
// Implement IDisposable
{
//just do the cleanup and release resources
GC.SuppressFinalize(this);
}
}