Created
April 30, 2012 09:19
-
-
Save AndrewBarfield/2556782 to your computer and use it in GitHub Desktop.
C#: IDisposable: Cleaning up managed and unmanaged resources
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 MyResource : IDisposable { | |
// Pointer to an external unmanaged resource. | |
private IntPtr handle; | |
// Other managed resource this class uses. | |
private Component component = new Component(); | |
// Track whether Dispose has been called. | |
private bool disposed = false; | |
// Class constructor. | |
public MyResource(IntPtr handle) { | |
this.handle = handle; | |
} | |
// Implement IDisposable. | |
public void Dispose() { | |
Dispose( true ); | |
GC.SuppressFinalize( this ); | |
} | |
private void Dispose(bool disposing) { | |
// Check to see if Dispose has already been called. | |
if ( !this.disposed ) { | |
// If disposing equals true, dispose all managed | |
// and unmanaged resources. | |
if ( disposing ) { | |
// Dispose managed resources. | |
component.Dispose(); | |
} | |
// Clean up | |
CloseHandle( handle ); | |
handle = IntPtr.Zero; | |
// Note disposing has been done. | |
disposed = true; | |
} | |
} | |
// Use interop to call the method necessary | |
// to clean up the unmanaged resource. | |
[System.Runtime.InteropServices.DllImport( "Kernel32" )] | |
private extern static Boolean CloseHandle(IntPtr handle); | |
// Use C# destructor syntax for finalization code. | |
~MyResource() { | |
Dispose( false ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment