The suggested dispose pattern from Microsoft says that Dispose() and finalizer should both call a virtual third method Dispose(bool). So it looks something like this:
public class DisposeBase : IDisposable
{
private bool _Disposed = false;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~DisposeBase()
{
Dispose(false);
}
protected virtual void Dispose(bool disposing)
{
if (!_Disposed)
{
if (disposing)
{
/* Get rid of managed resources */
}
/* Get rid of unmanaged resources */
_Disposed = true;
}
}
}
Derived classes would override Dispose(bool). I thought about restructuring it a bit like this:
public abstract class ExtendableResourceHandlerBase : IDisposable
{
private bool _Disposed = false;
/* private resources managed and unmanaged */
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~DisposeBase()
{
Dispose(false);
}
private void Dispose(bool disposing)
{
if (!_Disposed)
{
if (disposing)
{
ManagedDispose();
// Dispose of own managed resources
}
UnmanagedDispose();
// Dispose of own unmanged resources
_Disposed = true;
}
}
protected abstract void ManagedDispose();
protected abstract void UnmanagedDispose();
protected abstract xxx ExtendMe(....)
// other member functionality
}
I am thinking of scenario where in a framework you are declaring an abstract base class that provides an interface and some implementation aquiring resources that need to be disposed - hence the IDisposable
interface. Now clients extending this base class would be forced to think about the disposal of their managed and unmanaged resources as well. In the case of the suggested pattern from microsoft one might forget about it. Please think of the name ExtendableResourceHandlerBase
as just a place holder.
In my opinion this would make it easier for clients deriving from DisposeBase to implement their dispose methods. And as answers of another question show, other people think so too. The only reason I can think of why the good folks at microsoft build their pattern as it is now, is not to split up the disposal of managed and unmanaged resources. Are there any other reasons for it? Thanks alot for enlightening me.