Link to home
Start Free TrialLog in
Avatar of kishore_peddi
kishore_peddi

asked on

What is the difference between Finalize() and Dispose() ? (Which is used for managed / Unmanaged ?


Hi,

I want to know in simple terms what is the difference between Finalize() and Dispose() in Garbage collection. Which is used for MANAGED and UNMANAGED ?

Thanks,
Kishore
Avatar of richard_robinson
richard_robinson

Generally, Finalize is called by the Garbage Collector, and the state of manage objects cannot be guaranteed, so you should not reference them.
Also, you cannot determine when the GC will run, and which objects it will Finalize.

Dispose is called by the programmer, and is used to dispose of managed and unmanaged objects.
Within your dispose method, you release all of your resources and call GC.SuppressFinalize as you have done the work of the GC.

A good Design attern is available in MSDN help. Try searching for Implementing Dispose.

Have fun

RR
Hi

Finalize is like destructor. When the object is destroyed Finalize() will be called. And when GC collects the Object the object is destroyed. While dispose is your own method. Which you call to cleanup resources once you are sure that u have done with the object. .NET provide some support for efficient use of Dispose() e.g. IDispose interface and Using{} clause. If your class implement IDispose  and you have used Using clause Dispose is called as soon as scope of your object is out of Using!!

However I do not agree that we should NOT use Finalize(). We MUST use Dispose as well as Finalize(). But we should make sure that Dispose() is called every time. Because If finalize() is called the object is not collected immediately, the object will leave for one extra GC cycle if Finalise() is called. However from Dispose method we can suppress finalizer to avoid such performance hit. However if some one forgets to free resources by calling Dispose() finalize will make sure the resources are cleaned.

So Dispose() and Finalize() both are used for cleanup of UNMANAGED resources.
ASKER CERTIFIED SOLUTION
Avatar of nachiket
nachiket

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial