Created
September 8, 2012 16:08
-
-
Save davybrion/3676535 to your computer and use it in GitHub Desktop.
code snippets for ".NET Memory Management" 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 class MyDisposableClass : IDisposable | |
| { | |
| private bool disposed = false; | |
| public void Dispose() | |
| { | |
| Dispose(true); | |
| // prevent this object from being placed in the finalization queue if some | |
| // derived class provides a finalizer | |
| GC.SuppressFinalize(this); | |
| } | |
| protected virtual void Dispose(bool disposing) | |
| { | |
| if (!disposed) | |
| { | |
| if (disposing) | |
| { | |
| // dispose all Disposable Managed Resources here | |
| } | |
| // dispose all Unmanaged Resources here | |
| // set disposed to true to prevent the code above from being | |
| // executed a second time | |
| disposed = true; | |
| } | |
| } | |
| } |
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 ~MyDisposableClass() | |
| { | |
| Dispose(false); | |
| } |
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 void DoSomethingInteresting(MyDisposableClass disposableResource) | |
| { | |
| // ... some code could go here | |
| disposableResource.DoWhateverItIsThatMakesYouSoSpecial(); | |
| // ... some code could go here | |
| // we reach the end of the method and we haven't Disposed the | |
| // Disposable Managed Resource because it wasn't our responsibility | |
| } |
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 void DoSomethingInteresting() | |
| { | |
| // ... some code could go here | |
| using (var myDisposableResource = new MyDisposableClass()) | |
| { | |
| myDisposableResource.DoWhateverItIsThatMakesYouSoSpecial(); | |
| } | |
| // ... some code could go here | |
| // we reach the end of the method and we properly Disposed the | |
| // Disposable Managed Resource because it was our responsibility | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment