Skip to content

Instantly share code, notes, and snippets.

@davybrion
Created September 6, 2012 13:27
Show Gist options
  • Select an option

  • Save davybrion/3656247 to your computer and use it in GitHub Desktop.

Select an option

Save davybrion/3656247 to your computer and use it in GitHub Desktop.
code snippets for "Disposing of the IDisposable implementation" post
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() {}
}
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();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment