Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will GC.Collect() + GC.WaitForPendingFinalizers() ever NOT reclaim all reclaimable memory?

I'm trying to make sure instances of a certain class get released, by using console.WriteLine() in the destructor, but the output never shows up.

I have carefully searched for any lingering references, as well as event subscriptions and not finding any. Just for my own sanity, and before I continue my search, can someone confirm that:

GC.Collect();
GC.WaitForPendingFinalizers();

Will force a complete reclaim, no matter how small the objects are?

like image 756
Jamona Mican Avatar asked Sep 21 '12 17:09

Jamona Mican


People also ask

What does GC collect () do?

It performs a blocking garbage collection of all generations. All objects, regardless of how long they have been in memory, are considered for collection; however, objects that are referenced in managed code are not collected. Use this method to force the system to try to reclaim the maximum amount of available memory.

What is GC WaitForPendingFinalizers ()?

Suspends the current thread until the thread that is processing the queue of finalizers has emptied that queue. public: static void WaitForPendingFinalizers();

When should I call GC collect?

If you have code in your finalizers, it's possible that you will need to call GC. Collect() twice, as the first time will cause the finalizers to execute, but the actual memory cannot be cleaned until after the finalizer has completed, which means the subsequent call will catch the object.

When you request to GC to run it will start to run immediately True or false?

2 Answers. Show activity on this post. Calling GC. Collect() will do a complete garbage collection and wait for it to finish, but it will NOT wait for any pending finalizers to run.


1 Answers

In general, this should clean up most things.

However, if you have code in your finalizers, it's possible that you will need to call GC.Collect() twice, as the first time will cause the finalizers to execute, but the actual memory cannot be cleaned until after the finalizer has completed, which means the subsequent call will catch the object.

like image 149
Reed Copsey Avatar answered Sep 22 '22 02:09

Reed Copsey