C# Source Code: Overview of the IDisposable Interface and finalizers
[
Home
|
Contents
|
Search
|
Reply
| Previous | Next ]
C# Source Code
Overview of the IDisposable Interface and finalizers
By:
Andrew Baker
Email (spam proof):
Email the originator of this post
Date:
Thursday, April 22, 2004
Hits:
771
Category:
General/Framework
Article:
A class can expose a finalizer that executes when the object is destroted. The finalizer is a protected method and looks like this: protected void Finalize() { base.Finalize(); // Add clean up code here } Note, that you should always call base.Finalize before executing any of your own code. The .NET framework makes no guarantees about when it will call the objects finalizer because of the way it executes the finalization process. When an object with a finalizer is collected, it's not removed from memory. Instead it's placed in a special queue waiting for finalization. A dedicated thread is responsible for executing each objects finalizer. This thread makes then marks the object as no longer requiring finalization and removes it from the finalization queue. Until the finalizer has been called the queue's reference to the object is enough to keep the object alive, once this reference has been dropped the object will be picked up by the next pass of the garbage collector. Since there is no guaranteed order to finalization you should avoid making any references to objects managed on the heap (as they may have already been finalized). In general it is better to avoid using objects with finalizers as these objects are more costly to the Framework. They also maintain their existance through at least two garbage collection passes adding to the memory demands placed on the runtime. If you have an object which requires careful disposal then consider using the following pattern: //Demo Finalize & IDispose example public class MyDatabase: IDisposable { #region Class Clean up code() //Finalizer protected void Finalize() { Dispose(false); } //User has explicitly call Dispose public void Dispose() { Dispose(true); } //Clean up resources protected void Dispose(bool disposing) { if(disposing) { //Prevent the finalizer from being callled GC.SuppressFinalize(this); //Only dispose of managed objects here } //Release all external resouces, eg file handles etc. } #endregion }
Terms and Conditions
Support this site
Download a trial version of the best FTP application on the internet