.NET: Any way to tell when an object is deleted / garbage?

Given an object, is there a way to get notified when this object collects garbage?

I play with the fact that C # extension methods behave a little more than mixins (in particular when adding a log). Thus, basically every object gets a new Logger () method, which returns an ILog that is created and cached depending on the object that is the target of the extension method.

It works quite undulating, the only problem, obviously, after the object leaves, its registrar can hang out for a long time. I could, of course, create some periodic mechanism to scroll through the registrar cache and clear it, but I would rather set up a garbage collection notification to find out when the system no longer uses my objects.

Does anyone know how to do this?

+7
garbage-collection
source share
3 answers

I think it’s usually done here that you maintain a list of WeakReferences . With a weak reference, you can determine whether the object you are referencing was garbage collected or not collected by specifying the IsAlive property.

+11
source share

In .net 4.0, there is a type of ConditionalWeakTable , which can be used, although somewhat inconveniently, to request notification when an arbitrary object becomes suitable for completion. If a ConditionalWeakTable contains a record matching one object (say, the 451st object) with another object (for example, the created 730th object), then as long as the record remains in the table, and root links exist for both the table and and for object # 451, the table will be considered the root link to object # 730. If there is no anchor link for object # 451, the table will cease to be the root link to object # 730.

Therefore, if object # 730 contains a link to a table and object # 730 exists outside the table, object # 730 will have the right to finalize simultaneously with object # 451. If object # 730 overrides Finalize() , this override can be used as a notification that the object # 451 received the right to complete.

Note that the finalizer for object # 730 will fire only once, even if object # 451 resurrects itself and re-registers to complete. One could write code that will trigger a notification when object # 451 is indeed dead and buried, even if it is resurrected several times first, but there is no particularly clean way to do this.

+3
source share

The destructor is called during the GC.

+1
source share

All Articles