views:

120

answers:

3

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?

+10  A: 

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.

Dave Markle
+1, darn, stole my answer haha
kekekela
+1  A: 

The destructor is called during GC.

Darin Dimitrov
That's funny. I always heard them referred to as "Finalizers". Has the nomenclature changed, or was I just mistaken all this time?
Dave Markle
I think this depends on the language. It seems that in C#, *destructor* refers to the language construct that implements *finalization*. In C++/CLI however, the language construct called *destructor* (e.g. `~class() {...}`) actually implements the *IDispose* interface, while there is a new language construct called a *finalizer* (e.g. `!class() {...}`) which is the same as a *destructor* in C#.
stakx
Yeah, but that means I have to create a destructor that calls something like this.ReleaseLogger(). Not a bad idea, but something I'd prefer to avoid.
George Mauer
@Darin: actually the destructor is called _after_ the GC has detected that the object is unreachable, but _before_ the object memory is actually reclaimed (and the memory is reclaimed only if the object remain unreachable, as destructors have the power to reanimate dead objects).
Thomas Pornin
+2  A: 

Might want to check this out Garbage Collection Notifications

Dremation
That will only notify when a garbage collection happens, not when *specific* objects are garbage collected.
adrianbanks