You should use the IDisposable
pattern for your objects. The basic idea is this:
public class MyObject : IDisposable
{
// Some unmanaged resource:
UnmanagedResource unmanaged;
// Finalizer:
~MyObject
{
DisposeUnmanaged();
}
public void Dispose()
{
DisposeManaged();
DisposeUnmanaged();
GC.SuppressFinalize(this);
}
protected virtual DisposeManaged()
{
// Dispose _managed_ resources here.
}
protected virtual DisposeUnmanaged()
{
// Dispose _unmanaged_ resources here.
this.unmanaged.FreeMe();
this.unmanaged = null;
}
}
Then you can call Dispose
on your object as soon as you're sure it is no longer needed, and the unmanaged memory will be freed.
MyObject obj;
obj.Dispose();
Or, if you forget to call Dispose
, the unmanaged resources will be freed when the object is collected by the garbage collector (through the finalizer).