Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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!

like image 619
Tim Lovell-Smith Avatar asked May 14 '10 20:05

Tim Lovell-Smith


People also ask

When should WeakReference be used in garbage collection?

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.

Why do We use weakreferences?

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.

What is a weak reference and how could it be useful?

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.

How weak reference works?

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.


1 Answers

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.

like image 149
Stephen Cleary Avatar answered Oct 02 '22 09:10

Stephen Cleary