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!
You could easily implement a
WeakList<T>
class, which would wrap aList<WeakReference>
.There is no way to automatically remove objects when they are garbage collected, because it's not possible to detect when this happens. However, you could remove "dead" (garbage collected) objects when you encounter them, by checking the
WeakReference.IsAlive
property. However, I wouldn't recommend this approach, because it could lead to confusing behavior from the client's point of view. Instead, I would recommend implementing aPurge
method to remove dead entries, that you would call explicitly.Here's a sample implementation :
This class uses the following classes and extension methods :
WeakReference<T>
(just a strongly typed wrapper aroundWeakReference
)IndexOf
(same asIList<T>.IndexOf
, but works on aIEnumerable<T>
)CopyTo
(same asIList<T>.CopyTo
, but works on aIEnumerable<T>
)For anybody needing to use a ConditionalWeakTable in .NET 2.0 or 3.5 there is a backport of it here: https://github.com/theraot/Theraot/wiki/Features
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. TheWeakCollection<T>
class depends onWeakReference<T>
, which in turn depends onSafeGCHandle
.