Skip to content

Instantly share code, notes, and snippets.

@jcdickinson
Created December 3, 2012 18:22
Show Gist options
  • Save jcdickinson/4196875 to your computer and use it in GitHub Desktop.
Save jcdickinson/4196875 to your computer and use it in GitHub Desktop.
Disposers done right.
class IAmDisposable : IDisposable
{
private int _isDisposed;
private SomeDisposableThing _disposable1;
private SomeDisposableBar _disposable2;
private SomeDisposableBaz _disposable3;
// Only if you **need** it. You don't though, use SafeHandle.
//~IAmDisposable()
//{
// if (Interlocked.Exchange(ref _isDisposed, 1) == 0)
// {
// // NB: Do error handling.
// Dispose(false);
// }
//}
public void Dispose()
{
if (Interlocked.Exchange(ref _isDisposed, 1) == 0)
{
// NB: NO error handling here, users should know about any
// exceptions coming a from a Dispose() call.
GC.SuppressFinalize(this);
Dispose(true);
}
}
private void Dispose(bool disposing)
{
if (disposing)
{
// You technically don't need to interlocked the fields here,
// but meh, it's less code.
IDisposable tmp = Interlocked.Exchange(ref _disposable1, null);
if (tmp != null) tmp.Dispose();
tmp = Interlocked.Exchange(ref _disposable2, null);
if (tmp != null) tmp.Dispose();
tmp = Interlocked.Exchange(ref _disposable3, null);
if (tmp != null) tmp.Dispose();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment