-
-
Save denisbrodbeck/99194ca54289dd5296cf to your computer and use it in GitHub Desktop.
Disposers done right.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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