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.
Sign in to answer this question
It is the same account you read, post and publish with — and you will come straight back to this page.
Jean PaulPosted Nov 9, 2011, 7:52 AM
VulpesPosted Nov 9, 2011, 5:47 AM
Jean PaulPosted Nov 9, 2011, 2:09 AM
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.
Mamta MPosted Nov 9, 2011, 1:48 AM
Gyanendra Kumar MishraPosted Nov 9, 2011, 1:36 AM
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.