Finalize Method and Dispose Method

Kailash Chandra Behera | Sunday, August 07, 2016

Introduction

This article describes details about Finalize Method and Dispose Method,why we should prefer to use Dispose Method rather than Finalize Method while develping programming in c#.

Getting Started

.Net Framework almost does all clean up activity by Grabage collector for programing objects. But for some unmanaged resources (For example, Windows API created objects, File, Database connection objects, COM objects, etc) is outside the scope of .NET framework it has to explicitly clean resources. For these types of objects, .NET framework provides two methos Finalize Method and Dispose Method.

Finalize Method is Internally called by Garbage Collector and cannot be called by user code. It doesn't clean the memory immediately, hence there are performance costs associated with it. this Finalize method is belonged to the class and implemented with the help of destructor in C#.

Dispose Method is explicitly called by user code and it belongs IDisposable Interface, hence to use Dispose method in class that class must have to implement IDisposable interface.

It is always recommended not to use the Finalize method until it is extremely necessary, at runtime C# destructors are automatically converted to the Finalize method. Dispose method is the best way to clean unmanaged resources.

The problem with finalize is that garbage collection has to make two rounds in order to remove objects which have finalize methods. For example, let's say there are three objects: Object1, Object2, and Object3. Object2 has the finalize method overridden and remaining objects do not have the finalize method overridden.

When the garbage collector runs for the first time it searches for objects whose memory has to free. He can see three objects but only cleans the memory for Object1 and Object3. Object2 it pushes to the finalization queue. Then the garbage collector runs for the second time. The garbage collector gets to know there are no objects to be released and then checks for the finalization queue and at this moment, it clears object2 from the memory.

So if you notice that object2 was released from memory in the second round and not first. That is why the best practice is not to write clean up Non .NET resources in Finalize method rather use the DISPOSE.

Summary

In the above of this article we have discussed the Finalize, Dispose method and why we should prefere to use Dispose methos to release resources from memory. Hope this article may helpful to you.

Thanks