To surpass the disadvantage of finalizers another method is provided in .net framework i.e. Dispose. Using Dispose will not hurt your programs performance or kill the runtime time.
Differences between finalize and Dispose Methods.
Finalize method cannot be called explicitly, dotnet runtime calls this method implicitly to destruct the object. (In C#)
Dispose method Must be called explicitly at any time just like any other method. Contains the code to clean up the Unmanaged code accessed by the object.
No guarantee when the runtime executes the Fianlize method to destruct the object, though the object goes out of scope.
Dispose method Will be executed as soon as we call the method explicitly.
Since we cannot predict when the Finalize method is called, this type of collecting garbage is called non-deterministic finalization.
Since we dictate exactly when to collect garbage using Dispose method, this method is called deterministic finalization.
For a class to write the functionality of the Dispose method, the class must implement IDisposable interface.
So now you may ask me “why do we need finalize method when we have the Dispose method, which functions as good as a finalize method”. Here is the explanation for your doubt.
Assume that you had written a class in .net framework. This class uses a lot of unmanaged code and to clear the memory you had written a well functioning dispose method. So you will assume that everything is in place and will give the class to your friend to access.
Your friend in turn will access it. But he forgot to call the dispose method in the end. Then think what is going to happen……Memory Leakage. Why so, since your friend has used a lot of unmanaged code from your class and forgot to call the Dispose method and .net framework doesn’t know how to clean the unmanaged code.
To overcome such a case you will write your class with both dispose and finalize methods (finalize method will act as a backup method). In finalize method you will do nothing more than calling the dispose() method. In this case if your friend calls the dispose method, it will be well and good. If he forgets to call the dispose method, .net framework will call the finalize method while destructing the object. Eventually no memory leakage will be there.