Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Given an object, is there any way to get notified of when that object is garbage collected?

I am playing around with having C# extension methods behave a little more like mixins (specifically in adding logging). So basically each object gets a new Logger() method which returns an ILog that is created and cached depending on the object that is the extension method's target.

Works pretty swell, the only concern is obviously after an object goes away its logger might hang around for quite some time. I could of course set up some periodic mechanism to sweep through the logger cache and clear it but I would much rather set up some a Garbage-Collection notification so I learn about when the system is no longer using my objects.

Anyone know of a way to do this?

like image 544
George Mauer Avatar asked Mar 30 '10 17:03

George Mauer


3 Answers

I think what's generally done here is that you maintain a list of WeakReferences. With a weak reference, you can tell if the object you're referring to has been garbage-collected or not by checking the IsAlive property.

like image 200
Dave Markle Avatar answered Sep 17 '22 17:09

Dave Markle


In .net 4.0, there is a type ConditionalWeakTable which may be used, albeit somewhat awkwardly, to request notification when an arbitrary object becomes eligible for finalization. If a ConditionalWeakTable contains an entry mapping one object (say the 451st object created) to another object (say the 730th object created), then as long as the entry remains in the table, and rooted references exist both to the table and to object #451, the table will be considered a rooted reference to object #730. If no rooted reference exists to object #451, the table will cease to be a rooted reference to object #730.

Consequently, if object #730 holds a reference to the table and to object #730 exists outside the table, object #730 will become eligible for finalization at the same time as object #451. If object #730 overrides Finalize(), that override can be used as a notification that object #451 has become eligible for finalization.

Note that the finalizer for object #730 will only fire once even if object #451 resurrects itself and re-registers for finalization. It would be possible to write code which would fire notification around the time when object #451 truly becomes dead and buried, even if it gets resurrected a few times first, but there's no particularly clean way to do so.

like image 31
supercat Avatar answered Sep 18 '22 17:09

supercat


The destructor is called during GC.

like image 32
Darin Dimitrov Avatar answered Sep 21 '22 17:09

Darin Dimitrov