Everytime i need to implement the IDisposable interface i have to lookup the recommended way of doing so. That in itself is a bad sign, so i figured i might as well get rid of this by putting the implementation in a reusable base class, based on the officially recommended way:
public abstract class Disposable : IDisposable
{
private bool disposed;
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
DisposeManagedResources();
}
DisposeUnmanagedResources();
disposed = true;
}
}
protected void ThrowExceptionIfDisposed()
{
if (disposed)
{
throw new ObjectDisposedException(GetType().FullName);
}
}
protected abstract void DisposeManagedResources();
protected virtual void DisposeUnmanagedResources() {}
}
So now i can simply inherit from Disposable, and i just need to implement the two abstract methods. Here's a made up example to illustrate this:
public class MyExpensiveResource : Disposable
{
private FileStream fileStream;
private MemoryStream memoryStream;
public MyExpensiveResource(string path)
{
fileStream = new FileStream(path, FileMode.Open);
memoryStream = new MemoryStream();
}
public void DoSomething()
{
ThrowExceptionIfDisposed();
// ... something
}
protected override void DisposeManagedResources()
{
if (fileStream != null) fileStream.Dispose();
if (memoryStream != null) memoryStream.Dispose();
}
}
Obviously, you can't use the Disposable base class if you're already inheriting from another base class so in that case you'd still have to implement the IDisposable interface.
Update: Here's a thread-safe version of this idea.
Pingback: Quantum Bit Designs » Blog Archive » A Thread-Safe IDisposable Base Class
Pingback: Quantum Bit Designs » Blog Archive » A Thread-Safe IDisposable Base Class
Pingback: The Inquisitive Coder - Davy Brion’s Blog » Blog Archive » .NET Memory Management
Pingback: The Inquisitive Coder - Davy Brion’s Blog » Blog Archive » The Importance Of Releasing Your Components Through Windsor
Pingback: Code weave helper for the standard Dispose pattern? | FaceColony.org - Developers Network