C# Garbage Collecting – Destructors Versus Dispose
In C# it is illegal to call a destructor explicitly it must be called by the garbage collector. If you handle unmanaged resources that need to be closed and disposed of as soon as possible, you should implement the IDisposable interface. IDisposable requires implementers to define one method, named Dispose(), to perform the necessary cleanup routines.
If a Dispose() method is provided, you will need to stop the garbage collector calling your object’s destructor. To do this, call the static method GC.SuppressFinalize( ), and pass in the this pointer for your object. The destructor can then call Dispose( ) . Thus, you might write:
using System;
class TestDispose : IDisposable
{
bool isDisposed = false;
protected virtual void Dispose(bool disposing)
{
if (!isDisposed) // dispose only once!
{
if (disposing)
{
Console.WriteLine(
"Currently not in destructor, safe to reference other objects");
}
// cleanup
Console.WriteLine("Disposing now...");
}
this.isDisposed = true;
}
public void Dispose( )
{
Dispose(true);
// tell the Garbage Collector not to finalize
GC.SuppressFinalize(this);
}
~TestDispose( )
{
Dispose(false);
Console.WriteLine("In destructor.");
}
}












No comments yet... Be the first to leave a reply!