#425 – Nondeterministic Destruction and Object Finalization
October 4, 2011 8 Comments
In .NET, the CLR (Common Language Runtime) is responsible for reclaiming memory for objects that are no longer being referenced, through garbage collection.
Garbage collection can be done on an object as soon as it’s no longer being referenced by any other objects. However, the garbage collector may not free memory for an object immediately. It can choose to free up memory for an object whenever it likes.
Every object has a Finalize method that you can override, which will be called when the object is being destroyed. This method allows cleaning up any unmanaged resources the object might hold, before the object is destroyed.
The CLR implements nondeterministic destruction–you can’t explicitly force an object’s Finalize method to be called and you can’t predict when it is called. There’s also no guarantee that the finalizer will ever be called–an application might crash before the finalizer is called.