Search code examples
.netgarbage-collectionweak-references

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


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!


Solution

  • 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.