Open huoyaoyuan opened 6 months ago
Tagging subscribers to this area: @dotnet/area-system-runtime See info in area-owners.md if you want to be subscribed.
Author: | huoyaoyuan |
---|---|
Assignees: | - |
Labels: | `api-suggestion`, `area-System.Runtime`, `untriaged` |
Milestone: | - |
Instead of teaching the GC about this list, we can do what CWT does and clean-up the dead handles every time we grow the list's internal buffer.
Background and motivation
Weak references are widely used for tracking objects meanwhile allowing them to be collected by GC. In current API,
WeakReference<T>
provides decent support for tracking individual objects. There is also need for weakly tracking a collection of objects effectively. Sample usages include:The current workarounds for managing collections of weak references including:
ConditionalWeakTable
. The implementation ofArrayPool<T>.Shared
uses the key ofConditionalWeakTable<TKey, TValue>
to weakly track references. The value slots are not used and always set tonull
. This can lead to more overhead for the value field storing.WeakReference
together withConditionalWeakTable
. Example:WeakEventManager
of WPF.WeakReference
. When invoked, manually check each weak reference and remove collected ones.To simplify weak reference management and reduce potential overhead, collections of weak references are desired. BCL built-in support also provides more confidence of correctness and efficiency.
API Proposal
API Usage
Alternative Designs
Implement
ICollection<T>
,IList<T>
, or providing indexer ? Count and indexing are not clearly defined when some objects are collected by GC.Make the collection aware of GC, or make GC aware of the collection? Ideally, the self-cleanup should run when GC happens. For maximum memory efficiency, GC may specially recognize this collection and mark the object references inside it as "weak". When GC moves the storage of the collection, it can also compact it. This would require on-heap weak reference support, which can be very challenging. Making the collection aware of GC should be considerably simpler. It can use
WeakReference
orGCHandle
to track the objects, and skips collected objects during enumeration. Implicit trimming can be triggered for add, remove, or GC collecting events.Risks
The complexity and correctness when providing more integrated support from GC.