Sunday, June 9, 2013

Dispose Vs Finalize

Both Dispose and Finalize are used to release un-managed resources, however there are many differences between the way Dispose and Finalize operates.

The Dispose() method should be explicitly defined in the class, and the program using the instance of the class should explicitly call the Dispose method.

Finalize is not explicitly defined, Finalize code is written in the destructor of the class, and is called automatically when Garbage Collection runs.
Dispose releases the memory of the un-managed objects immediately, while Finalize releases the memory just before the object is to be destroyed. The cleanup code written in Finalize block, will not get executed till such time Garbage Collection runs and identifies the object for disposal.

Since Dispose and Finalize does the same job, both should not be called, we know that Dispose gets called before Finalize, hence we add the following line of code in the Dispose method to make sure that Finalize does not get executed for the object.


In order to define the Dispose method the class should implement the IDisposable interface, but Finalize block has no such conditions, Finalize code can be written directly in the destructor of the class.

Dispose methods are explicit methods which should be called from the code to dispose un-managed resources, while Finalize is a safeguard mechanism, in case the user code fails to call dispose, Garbage Collection will automatically call Finalize and dispose the un-managed resources.

Search Flipkart Products:

No comments: