#425 – Nondeterministic Destruction and Object Finalization

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.


About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

8 Responses to #425 – Nondeterministic Destruction and Object Finalization

  1. Pingback: #426 – Use a Destructor to Free Unmanaged Resources « 2,000 Things You Should Know About C#

  2. Pingback: #921 – Objects Are Explicitly Created but Automatically Destroyed | 2,000 Things You Should Know About C#

  3. Pingback: #923 – An Object Isn’t Necessarily Deleted as Soon as Its Dereferenced | 2,000 Things You Should Know About C#

  4. Pingback: #940 – Finalizers Are Called when an Application Shuts Down | 2,000 Things You Should Know About C#

  5. typo – “you’d can’t predict” s/b “you can’t predict”

  6. Actually you Can force an immediate garbage collection: GC.Collect(); but you Shouldn’t.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: