Created
September 10, 2013 18:07
-
-
Save gscattolin/6513222 to your computer and use it in GitHub Desktop.
Dispose Good Practice
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
| Type That Owns Disposable Fields Implements IDisposable: Good Practice | |
| public class OwnsDisposableFields : IDisposable | |
| { | |
| private DisposableResource disposableResourceOne; | |
| private DisposableResource disposableResourceTwo; | |
| // Other fields continue to be declared here. | |
| private bool disposed; | |
| ~OwnsDisposableFields() | |
| { | |
| Dispose(false); | |
| } | |
| public void OperationThatAllocatesResources() | |
| { | |
| disposableResourceOne = new DisposableResource(); | |
| disposableResourceTwo = new DisposableResource(); | |
| } | |
| // The System.IDisposable.Dispose method. | |
| public void Dispose() | |
| { | |
| Dispose(true); | |
| // Use SupressFinalize in case a subclass of this one | |
| // implements a finalizer. | |
| GC.SuppressFinalize(this); | |
| } | |
| protected virtual void Dispose(bool disposing) | |
| { | |
| // If you need thread safety, use a lock around these | |
| // operations, as well as in your methods that use the resource. | |
| // Protect from being called multiple times. | |
| if (disposed) | |
| { | |
| return; | |
| } | |
| if (disposing) | |
| { | |
| // Clean up all managed resources | |
| if (this.disposableResourceOne != null) | |
| { | |
| // Release managed resources | |
| this.disposableResourceOne.Dispose(); | |
| // Free the unmanaged resource | |
| this.disposableResourceOne = null; | |
| } | |
| if (this.disposableResourceTwo != null) | |
| { | |
| // Release managed resources | |
| this.disposableResourceTwo.Dispose(); | |
| // Free the unmanaged resource | |
| this.disposableResourceTwo = null; | |
| } | |
| } | |
| disposed = true; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment