Skip to content

Instantly share code, notes, and snippets.

@denisbrodbeck
Forked from jcdickinson/IAmDisposable.cs
Created December 15, 2015 21:04
Show Gist options
  • Select an option

  • Save denisbrodbeck/99194ca54289dd5296cf to your computer and use it in GitHub Desktop.

Select an option

Save denisbrodbeck/99194ca54289dd5296cf to your computer and use it in GitHub Desktop.

Revisions

  1. Jonathan Dickinson created this gist Dec 3, 2012.
    43 changes: 43 additions & 0 deletions IAmDisposable.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,43 @@
    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();
    }
    }
    }