Click here to hide categories Click here to show left categories

User: Home          welcome : Guest          Log In / Register here     




.Net interview questions: - Can you explain why is it preferred to not use finalize for clean up?

Problem with finalize is that garbage collection has to make two rounds in order to remove objects which have finalize methods.

Below figure will make things clear regarding the two rounds of garbage collection rounds performed for the objects having finalized methods.

Figure: - Garbage collection in actions

In this scenario there are three objects Object1, Object2, and Object3. Object2 has the finalize method overridden and remaining objects do not have the finalize method overridden.

Now when 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.

Now garbage collector runs for the second time. He see’s 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.

See the following video in .NET which describes regular expressions & some practical demonstrations: -

Click for more .NET Interview questions

Regards,

Visit for more authors’ blog on .NET Interview questions

Share this article   |    Print    |    Article read by 4282 times
Author:
Shivprasad koirala Koirala
I am a Microsoft MVP for ASP/ASP.NET and currently a CEO of a small E-learning company in India. We are very much active in making training videos , writing books and corporate trainings. Do visit my site http://www.questpond.com for .NET, C# , design pattern , WCF , Silverlight , LINQ , ASP.NET , ADO.NET , Sharepoint , UML , SQL Server training and Interview questions and answers
Related Articles:
Related Interview Questions: