Is there any downside of calling GC.SuppressFinalize(object)
multiple times?
Protected Dispose(bool)
method of the dispose pattern checks whether it is called before but there is no such check in the public Dispose()
method.
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (_Disposed)
return;
if (disposing)
{
// Cleanup managed resources.
}
// Cleanup unmanaged resources.
_Disposed = true;
}
~MyClass() { Dispose(false); }
Is it ok to call the Dispose()
method of a MyClass
instance multiple times?
A correctly implemented Dispose method can be called multiple times without throwing an exception. However, this is not guaranteed and to avoid generating a System. ObjectDisposedException you should not call Dispose more than one time on an object.
Dispose should call GC. SuppressFinalize so the garbage collector doesn't call the finalizer of the object. To prevent derived types with finalizers from having to reimplement IDisposable and to call it, unsealed types without finalizers should still call GC.
GC. SuppressFinalize to prevent the garbage collector from implicitly invoking the finalizer a second time. Do not directly call your base class Finalize method. It is called automatically from your destructor.
According to docs: http://msdn.microsoft.com/en-us/library/system.gc.suppressfinalize.aspx, it sets some bit in object header, so there shouldn't be any implications of calling it multiple times.
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