Finalize and Dispose

-> They are used to clean up unmanaged resources.
-> Class instances often encapsulate control over resources that are not managed by the run time, such as windows handles (HWND), database connections and so on. Therefore we should provide both an explicit and implicit way to free those resources.
-> We can provide implicit control by implementing the protected Finalize on an object (destructor). The garbage collector calls this method at some point after there are no longer any valid references to the object.
-> In some cases, we might want to provide programmers using an object with the ability to explicitly release these external resources before the garbage collector frees the object. If and 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 provided by IDisposable. The consumer of the object should call this method when it is finished using the object. Dispose can be called even if other references to the object are alive.
-> Even when you provide explicit control using Dispose, you should provide implicit clean up using the Finalize method. Finalize provides a back up to prevent resources from permanently leaking if the programmer fails to call Dispose.

Dispose Finalize
It is used to free unmanaged resources like files, database connections etc. at any time. It can be used to free unmanaged resources (when you implement it) like files, database connections etc. held by an object before that object is destroyed.
Explicitly, it is called by user code and the class which is implementing dispose method, must has to implement IDisposable interface. Internally, it is called by Garbage Collector and cannot be called by user code.
It belongs to IDisposable interface. It belongs to Object class.
It’s implemented by implementing IDisposable interface Dispose() method. It’s implemented with the help of destructor in C++ & C#.
There is no performance costs associated with Dispose method. There is performance costs associated with Finalize method since it doesn’t clean the memory immediately and called by GC automatically.

Leave a Reply

Your email address will not be published. Required fields are marked *