#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.
Pingback: #426 – Use a Destructor to Free Unmanaged Resources « 2,000 Things You Should Know About C#
Pingback: #921 – Objects Are Explicitly Created but Automatically Destroyed | 2,000 Things You Should Know About C#
Pingback: #923 – An Object Isn’t Necessarily Deleted as Soon as Its Dereferenced | 2,000 Things You Should Know About C#
Pingback: #940 – Finalizers Are Called when an Application Shuts Down | 2,000 Things You Should Know About C#
typo – “you’d can’t predict” s/b “you can’t predict”
Thanks
Actually you Can force an immediate garbage collection: GC.Collect(); but you Shouldn’t.
Agreed. There’s a “under normal circumstances” phrase implicit in my wording.