Subscribe

RSS Feed (xml)

Powered By

Skin Design:
Free Blogger Skins

Powered by Blogger

Search Your Question

Tuesday, May 6, 2008

What is the difference between Finalize and Dispose (Garbage collection) ?

Resources like database connections, file and window handles (HWND) often are not managed by the runtime. Therefore, we should provide both an explicit and an implicit way to free these resources.
The garbage collector calls Finalize method at some point after there are no longer any valid references to the object.
However In some cases, 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() method provided by the IDisposable Interface. The consumer of the object should call this method when it is done using the object.
Dispose can be called even if other references to the object are alive.
Note that even when you provide explicit control by way of Dispose, you should provide implicit cleanup using the Finalize method.

Finalize prevent resources from permanently leaking if the programmer fails to call Dispose.

No comments:

Archives