Dispose pattern (C#)

Microsoft has defined a formal, prim-and-proper disposal pattern that strikes a balance between robustness, maintainability, and performance.

Here is a sample which makes use of this official pattern.

    public class MyResourceWrapper : IDisposable
{
// Used to determine if Dispose()
// has already been called.
private bool disposed = false;
public void Dispose()
{
// Call our helper method.
// Specifying "true" signifies that
// the object user triggered the cleanup.
CleanUp(true);
// Now suppress finalization.
GC.SuppressFinalize(this);
}
private void CleanUp(bool disposing)
{
// Be sure we have not already been disposed!
if (!this.disposed)
{
// If disposing equals true, dispose all
// managed resources.
if (disposing)
{
// Dispose managed resources.
}
// Clean up unmanaged resources here.
}
disposed = true;
}
~MyResourceWrapper()
{
// Call our helper method.
// Specifying "false" signifies that
// the GC triggered the cleanup.
CleanUp(false);
}
}
Source: Pro C# 2008 and the .NET 3.5 Platform (Fourth Edition)

posted under , , |
Newer Post Older Post Home
This is my personal blog to share my research on Web related Technologies as well as Inner Well Being.