Suppose I have a WeakReference of a target strong reference. I’d like to be informed when the target object itself is being collected by the GC. Is it possible?
EDIT: Adding code to the finalizer/destructor is not an option here. I need something that is not dependent on class code.
It’s possible under .NET 4.0 and following using
ConditionalWeakTable<TKey, TValue>. Thanks this, and other sites. It follows proof of concept code:Tested with the following code: