Thursday, January 7, 2010

Difference B/W Finalize() and Dispose() in .Net?

Both are ways to destroy the object. By object i mean when you have some unmanaged resources used in your class, you have to make sure that you write the logic to destroy them in the finalize() method. But this is the implicit way of destroying the unmanaged resources, as finalize is called by garbage collector when it find thats there is no reference to this object from the stack. There is an explicit way to destroy the unmanaged resources. That is by implementing IDisposable interface. By implementing this interface, ie you have to write the code to destroy the resource in Dispose() method, you can call the object to destroy itself when ever required in your code.when we write the destructor in c#,the runtime replaces the destructor with the finalize method in IL code,so we dont know at what time the destructor is called by the garbage collector.so the finalizer is non deterministic.if we want to do the garbage collection for unmanages resources,we have to implement our own destructor or finlizer method.but,the runtime will take two round trips to remove those objects from the heap.if runtime calls the own destructor,it will take onely one round trip. to remove the unmanaged resources without the performance issues,we have to inherit the System.Idisposable interface and implement the Dispose() method.here one problem is there,we have to write a code in a way that,the dsipose method must and should execute. for that reason we have to keep the dispose methos for the objcets in the finally block. problem with the dispose is that,some times because of some problmes dispose() methos may not execute. so the good practice is to use both to achieve the desied performance.

No comments:

Post a Comment