Created
August 18, 2019 16:44
-
-
Save luisdeol/99d5d3f66c971f621913ecce37775bfe to your computer and use it in GitHub Desktop.
Dispose pattern (from Microsoft docs)
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
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