Information Technology Reference
In-Depth Information
leak resources when they forget. It's their fault for not calling Dispose, but
you'll get the blame. The only way you can guarantee that unmanaged
resources get freed properly is to create a finalizer. So create one.
When the Garbage Collector runs, it immediately removes from memory
any garbage objects that do not have finalizers. All objects that have final-
izers remain in memory. These objects are added to a finalization queue,
and the Garbage Collector spawns a new thread to run the finalizers on
those objects. After the finalizer thread has finished its work, the garbage
objects can be removed from memory. Objects that need finalization stay
in memory for far longer than objects without a finalizer. But you have no
choice. If you're going to be defensive, you must write a finalizer when
your type holds unmanaged resources. But don't worry about perform-
ance just yet. The next steps ensure that it's easier for clients to avoid the
performance penalty associated with finalization.
Implementing IDisposable is the standard way to inform users and the
runtime system that your objects hold resources that must be released in
a timely manner. The IDisposable interface contains just one method:
public interface IDisposable
{
void Dispose();
}
The implementation of your IDisposable.Dispose() method is responsi-
ble for four tasks:
1. Freeing all unmanaged resources.
2. Freeing all managed resources (this includes unhooking events).
3. Setting a state flag to indicate that the object has been disposed. You
need to check this state and throw ObjectDisposed exceptions in your
public methods, if any get called after disposing of an object.
4. Suppressing finalization. You call GC.SuppressFinalize(this) to
accomplish this task.
Yo u a c c o m p l i s h t w o t h i n g s b y i m p l e m e n t i n g I D i s p o s a b l e : Yo u p r o v i d e t h e
mechanism for clients to release all managed resources that you hold in a
timely fashion, and you give clients a standard way to release all unman-
aged resources. That's quite an improvement. After you've implemented
IDisposable in your type, clients can avoid the finalization cost. Your class
is a reasonably well-behaved member of the .NET community.
 
Search WWH ::




Custom Search