Created
April 27, 2016 16:39
-
-
Save Thesharing/9785a8b0f43fe7d25abd21f434d887f7 to your computer and use it in GitHub Desktop.
正确的IDisposable实现方式
This file contains 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 Resource : IDisposable | |
{ | |
private IntPtr nativeResource = Marshal.AllocHGlobal(100); | |
private AnotherResource managedResource = new AnotherResource(); | |
// Dispose() calls Dispose(true) | |
public void Dispose() | |
{ | |
Dispose(true); | |
GC.SuppressFinalize(this); | |
} | |
// NOTE: Leave out the finalizer altogether if this class doesn't | |
// own unmanaged resources itself, but leave the other methods | |
// exactly as they are. | |
~Resource() | |
{ | |
// Finalizer calls Dispose(false) | |
Dispose(false); | |
} | |
// The bulk of the clean-up code is implemented in Dispose(bool) | |
protected virtual void Dispose(bool disposing) | |
{ | |
if (disposing) | |
{ | |
// free managed resources | |
if (managedResource != null) | |
{ | |
managedResource.Dispose(); | |
managedResource = null; | |
} | |
} | |
// free native resources if there are any. | |
if (nativeResource != IntPtr.Zero) | |
{ | |
Marshal.FreeHGlobal(nativeResource); | |
nativeResource = IntPtr.Zero; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment