Dispose method and Finalize method
Class instances often encapsulate control over
resources that are not managed by the runtime, such as window handles (HWND),
database connections, and so on. Therefore, you should provide both an explicit and an implicit way to free
those resources.
Provide implicit
control by implementing the protected Finalize on
an object (destructor syntax in C# and C++). The garbage collector calls this
method at some point after there are no longer any valid references to the
object.
In some cases, you might want to provide programmers
using an object with the ability to explicitly release these external resources
before the garbage collector frees the object. If an external resource is
scarce or expensive, better performance can be achieved if the programmer
explicitly releases resources when they are no longer being used. To provide
explicit control, implement the Dispose provided
by the IDisposable.
The consumer of the object should call this method when it is finished using
the object. Dispose can
be called even if other references to the object are alive.
Note that even when you provide explicit control using Dispose, you should provide implicit cleanup using the Finalize method. Finalize provides
a backup to prevent resources from permanently leaking if the programmer fails
to call Dispose.
For more information about implementing Finalize and Dispose to
clean up unmanaged resources, see Garbage Collection. The following example illustrates the basic design pattern for
implementing Dispose. This
example requires the System namespace.
//Base Class Design Pattern
public class Base : IDisposable
{
private bool disposed = false;
//Implement
IDisposable.
public void Dispose()
{
}
protected virtual void Dispose(bool disposing)
{
if(!disposed)
{
if(disposed)
{
// Free Other State ( managed resources)
}
//
Free your own state (unmanaged objects).
//
Set large fields to null.
disposed = true;
}
}
~Base ()
{
Dispose(false);
}
}
//
Design Pattern for Derived class
public class Derived: Base
{
private bool disposed = false;
protected override void Dispose(bool disposing)
{
if(!disposed)
{
if(disposed)
{
// Release managed resources.
}
//
Release unmanaged resources.
//
Set large fields to null.
//
Call Dispose on your base class.
disposed = true;
}
base.Dispose(disposing);
}
// The
derived class does not have a Finalize method
// or a
Dispose method without parameters because it inherits
// them
from the base class.
}
Comments
Post a Comment