Skip to content

Instantly share code, notes, and snippets.

@luisdeol
Created August 18, 2019 16:44
Show Gist options
  • Save luisdeol/99d5d3f66c971f621913ecce37775bfe to your computer and use it in GitHub Desktop.
Save luisdeol/99d5d3f66c971f621913ecce37775bfe to your computer and use it in GitHub Desktop.
Dispose pattern (from Microsoft docs)
using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.InteropServices;
namespace _26_ManageObjLifecycle
{
class BaseClass : IDisposable
{
// Flag: Has Dispose already been called?
bool disposed = false;
// Instantiate a SafeHandle instance.
SafeHandle handle = new SafeFileHandle(IntPtr.Zero, true);
// Public implementation of Dispose pattern callable by consumers.
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
// Protected implementation of Dispose pattern.
protected virtual void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing)
{
handle.Dispose();
// Free any other managed objects here.
//
}
disposed = true;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment