Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are there any events that tell an application when garbage collection has occurred?

I am trying to find a way to know about garbage collection. Either, when it has started, finished or is in process. I really just need some event connected to the collection itself (I think).

My issue is that I have a WeakEventManager (written from scratch) and I have cleanup methods that delete and WeakReferences that are no longer alive (WeakReferences are in a Dictionary).

The issue is that I have to know when it is time to "clean up". It would be nice to cleanup when the collector is doing its thing. Even if it is after the garbage collection, at least the next collection will remove these old objects.

like image 382
Phobis Avatar asked Nov 30 '22 20:11

Phobis


2 Answers

The System.GC class offers a RegisterForFullGCNotification method which will allow notifications to be raised when garbage collection is about to be done, and when it's been completed.

It's not ideal, as there are a few caveats to using this method, such as concurrent garbage collection must be disabled for this method to work.

Please see the following links for full info:

Garbage Collection Notifications

GC.RegisterForFullGCNotification Method

like image 145
CraigTP Avatar answered Dec 05 '22 00:12

CraigTP


You could monitor the .NET Memory performance counter object. There are counts for number of gen 0, 1, and 2 collections.

Generally on a GC based system, directly referencing the GC is something of an anti-pattern. You would likely (given the limited description) be better just lazily cleaning up when you try and used a cleared WeakReference.

like image 21
Richard Avatar answered Dec 04 '22 23:12

Richard