Implement Dispose() properly
The following illustrates how to properly implement the Dispose() function for a class which has the IDisposable interface:public class MyClass : IDisposable
{
public void Dispose()
{
this.Dispose(true);
// Call SupressFinalize in case a subclass implements a finalizer.
GC.SuppressFinalize(this);
}
private bool m_bDisposed = false;
protected virtual void Dispose(bool disposing)
{
// If you need thread safety, use a lock around these
// operations, as well as in your methods that use the resource.
do
{
// if the object is already disposed, get out now.
if (this.m_bDisposed) break;
if (disposing)
{
// dispose of all local objects here.
}
// Set flat to indicate that the instance has been disposed.
this.m_bDisposed = true;
} while (false);
}
}
Last modified by Mohit @ 4/4/2025 9:31:06 PM