Deterministic Finalisation in Csharp
I want to perform deterministic Finalisation in Csharp. How can I do that
Know the answer? Post it. Somebody with the same question will find it here.
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questions
DevSocialUpcoming · 3rd editionAI Agents ConferenceDec 1–3, 2026Live onlineFree to attend5days leftRegister
Gyanendra Kumar Mishra15 reputationPosted Nov 8, 2011, 8:36 PM EST
You can deterministically finalize any object that implements the IDisposable interface by invoking its Dispose() method. If you use C# you have the advantage of the using statement which allows you to define a scope at the end of which an object will be disposed. One of the most common examples given uses a SqlConnection object:
using ( SqlConnection test = newSqlConnection( ... ) ) {
// code implementation
} // SqlConnection.Dispose() is automatically invoked
At the end of this scope, the SqlConnection's Dispose() method is automatically invoked and all resources held by this object are released.
Mamta MRank #268 · 9.4K reputationPosted Nov 8, 2011, 8:48 PM EST
Jean PaulRank #32 · 38.5K reputationPosted Nov 8, 2011, 9:09 PM EST
The Destructor and Finalize() are almost the same. The Destructor are converted into Finalize() method in the IL code.
Destructors are automatically called by the Garbace Collector and it is non-deterministic. But in certain cases we need to take control of it. (usually when dealing with unmanaged resources)
You can refer the article here: http://www.codeproject.com/KB/cs/NDestructors.aspx
GC.SuppressFinalize(this); // Call this inside the Dispose() method
There is also GC.KeepAlive(this); which is used to keep the instance alive even if no other object are refererring to it.
VulpesRank #55 · 29.2K reputationPosted Nov 9, 2011, 12:47 AM EST
Jean PaulRank #32 · 38.5K reputationPosted Nov 9, 2011, 2:52 AM EST