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?
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.
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.
The destructor is called during GC.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With