Here is the typical IDisposable implementation that I believe is recommended:
~SomeClass() {
Dispose(false);
}
public void Dispose() {
GC.SuppressFinalize(this);
Dispose(true);
}
protected virtual void Dispose(bool isDisposing) {
if(isDisposing) {
// Dispose managed resources that implement IDisposable.
}
// Release unmanaged resources.
}
Now, to my understanding, the idea behind the finalizer there is that if I don't call Dispose, my unmanaged resources will be released properly still. However, to my knowledge, it is generally agreed upon that not calling Dispose on an object that implements IDisposable is probably a bug.
Is there a particular reason not to fully embrace this and do this instead?
~SomeClass() {
throw new NotImplementedException("Dispose should always be called on this object.");
}
public virtual void Dispose() {
GC.SuppressFinalize(this);
// Dispose managed resources that implement IDisposable.
// Release unmanaged resources.
}
From .NET 2.0 and on, An unhandled Exception thrown in a Finalizer causes the process to terminate if the default policy is not overridden.
To my understanding, a Finalizer is not an expected location where an Exception should be thrown. I think it is possible for a Dispose()
method not to have been called for an unexpected reason (Thread abort, ...) from which a clean recovery is still possible, provided that the Finalizer executes properly.
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