I use a default IDisposable implementation template (pattern) for my code.
snippet:
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;
}
}
My question: why is the call "GC.SuppressFinalize(this)" in the Dispose public method? I would place "GC.SuppressFinalize(this)" in the "if (isDisposing)" section of the protected method, after disposing managed resources.
Like this:
protected virtual void Dispose(bool isDisposing)
{
if (!this.disposed)
{
if (isDisposing)
{
//cleanup managed resources
GC.SuppressFinalize(this);
}
//cleanup unmanaged resources
this.disposed = true;
}
}
The Dispose(bool isDisposing)
method isn't part of the IDisposable
interface.
You would normally call Dispose(true)
from your Dispose
method, and call Dispose(false)
from your finalizer, as a fallback in the case where the object hasn't already been disposed.
Calling SuppressFinalize
tells the GC that there's no need to call your object's finalizer, presumably because all your cleanup was done when Dispose
was called.
If you don't have a finalizer on your class, then you don't need to call SuppressFinalize
at all, since there's no finalizer to suppress!
Joe Duffy has some great guidelines on disposal, finalization, garbage collection etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With