Skip to content

Instantly share code, notes, and snippets.

@davybrion
Created September 8, 2012 16:08
Show Gist options
  • Select an option

  • Save davybrion/3676535 to your computer and use it in GitHub Desktop.

Select an option

Save davybrion/3676535 to your computer and use it in GitHub Desktop.
code snippets for ".NET Memory Management" post
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;
}
}
}
public ~MyDisposableClass()
{
Dispose(false);
}
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
}
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