Created
September 6, 2012 13:27
-
-
Save davybrion/3656247 to your computer and use it in GitHub Desktop.
code snippets for "Disposing of the IDisposable implementation" post
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
| 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() {} | |
| } |
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
| 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