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!
A weak reference permits the garbage collector to collect the object while still allowing the application to access the object. A weak reference is valid only during the indeterminate amount of time until the object is collected when no strong references exist.
Weak reference objects, which do not prevent their referents from being made finalizable, finalized, and then reclaimed. Weak references are most often used to implement canonicalizing mappings. Suppose that the garbage collector determines at a certain point in time that an object is weakly reachable.
A weak reference allows the garbage collector to collect an object while still allowing an application to access the object. If you need the object, you can still obtain a strong reference to it and prevent it from being collected.
An object referenced only by weak references – meaning "every chain of references that reaches the object includes at least one weak reference as a link" – is considered weakly reachable, and can be treated as unreachable and so may be collected at any time.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With