Search code examples
c#.netclrobject-lifetime

Get notification of object disposal/destruction


I need a way to track instances of various classes, without those classes having any knowledge that they are being tracked. Essentially, I have a class factory which creates instances and hands them off to another thread. Once that thread completes and unloads the instance, I need to get notified of that so I can do reference counting and exit from my class factory when all the instances are gone.

The challenge is that I can't modify any of the classes I'll bve loading, because I don't control their source code.

Tracking the instances I create is simple, I can just put them in some sort of collection as I create them. Tracking their destruction is causing me problems. If I could modify the source code, I'd add an event to each class and when I create an instance, I'd hook into the event and use that as my notification. But I can't do that.

So, the question is this: is there a sneaky way to monitor an object instance and detect when it is being destroyed?


Solution

  • There isn't a way to get active notification, but you could keep a WeakReference to the objects and periodically check if any have died.

    Edit: I like Reed's answer better than mine!