Is there a way to do a WeakList or WeakCollection (like WeakReference) in CLR?

Tim Lovell-Smith picture Tim Lovell-Smith · May 14, 2010 · Viewed 9.5k times · Source

Using a List<WeakReference> will not work as I want. What I want is for WeakReferences to be automatically removed from the list whenever the object they reference is garbage collected.

ConditionalWeakTable<TKey,TValue> does not satisfy me either, because although its keys and values are weakly referenced and collectable, you cannot enumerate them!

Answer

Stephen Cleary picture Stephen Cleary · May 14, 2010

I agree that implementing a WeakList<T> is possible, but I don't think it's exactly easy. You're welcome to use my implementation here. The WeakCollection<T> class depends on WeakReference<T>, which in turn depends on SafeGCHandle.