December 28, 2004

Finalize vs Dispose


1. Finalizer same as destructor in C++ however get executed on different (GC) thread. Therefore there is no guarantee of immediate clean up using finalizer.

2. Objects takes at least two GC clean up cycles to execute finalize.

3. Nondeterministic invocation.

4. If object does not get cleared in first generation then it gets promoted in next generation which causes pressure on CLR.


1. IDispose is better way to clean up unmanaged objects than finalize.

2. No connection with GC.

3. However need to call externally as compared to Finalize.

Using both Dispose and Finalize

If Dispose() not gets called externally then object may not get cleanup properly. To solve this write clean up code in separate routine and call it from Dispose() as well as Finalize(). In Dispose() make sure to call GC.SuppressFinalize() before exiting the dispose method for that object. This will prevent calling of finalize method and cleanup code again.