The prefered way to release an object is to implement IDisposable and have a Dispose() method. Dispose() needs to be called by the programmer explicitly. On the other hand, Finalizer is executed by the GC and we dont need to implement any interface or something like that. But we should avoid Finalizer because :
1) Finalizer is non-deterministic. Since it is called by GC, we can not say perticularly when it will execute.
2) Finalizer makes slower the execution of GC.
3) The thread on which the finalizer will be called is not specified.
4) We should not access managed resources in Finalizar. Because those managed resources could be finalized before-hand.
You may ask then "Why should I implement Finalize then?". I will say, if your class uses some expensive unmanaged system resources (eg, file-handle), then you should implement it. The reason is, Dispose() needs be called explicitly. So if the programmer forgets to call Dispose() or due to some exception in other code, Dispose() doesnt get called, then? Then no other classes will be able to use those system resources. But if you implement Finalize, then altleast after a certain time (when the object will be collected by GC), those system resources will be freed.
Here is the best practice (generalized):
public class MyObjectGC : IDisposable { // Track whether Dispose has been called. private bool disposed = false;
// Constructor. public MyObjectGC() { // allocate some unmanaged resources. // allocate some managed resources. }
// Destructor/Finalizer ~MyObjectGC() { // dispose only unmanaged resources. Dispose( false ); }
public void Dispose() { // dispose all managed & unmanaged resources. Dispose( true ); // Call GC.SupressFinalize to take this object off // the finalization queue because it is already // disposed explicitly. GC.SuppressFinalize(this); }
private void Dispose( bool disposingManagedResources ) { // Check to see if Dispose has already been called. if( !this.disposed ) { if( disposingManagedResources ) { // Dispose all managed resources. } // dispose all unmanaged resources. disposed = true; } } }
|
| Author: jpatel 22 Dec 2004 | Member Level: Bronze Points : 0 |
Is there any sequence to dispose object from memory that is used by GC ? eg : life cycle ..like: start load finlize unload dispose ???? plz if anybody knows... Thanks in advance.
|