Skip to content

Instantly share code, notes, and snippets.

@programmation
Created May 4, 2015 04:23
Show Gist options
  • Save programmation/2dbaab4c8399884a2b58 to your computer and use it in GitHub Desktop.
Save programmation/2dbaab4c8399884a2b58 to your computer and use it in GitHub Desktop.
Unmanaged resource holder template
// http://blog.adamkemp.com/2014/10/c-finalizers-and-idisposable.html
public class UnmanagedResourceHolder : IDisposable
{
private bool _disposed;
private OtherDisposableObject _otherDisposable;
public UnmanagedResourceHolder()
{
AcquireUnmanagedResource();
}
~UnmanagedResourceHolder()
{
Dispose(disposing: false);
}
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
// In a sealed class, use private (doesn't need to be virtual)
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
_disposed = true;
ReleaseUnmanagedResource();
if (disposing)
{
if (_otherDisposable != null)
{
_otherDisposable.Dispose();
_otherDisposable = null;
}
}
}
}
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment