In some situations involving immutable objects, it will be possible for many distinct objects to come into existence which are semantically identical. A simple example woul
You could create something like Dictionary<WeakReference, WeakReference>
with a custom equality comparer and prune those that are no longer alive at appropriate times. One problem with that is how to remove a dead WeakRefrence
from the dictionary, because you can't remove it by reference equality (remember, you have to use custom equality comparer) or index. Possible solutions are creating a type that inherits from WeakReference
and has correct hash code even if the reference is dead. Or you could wrap it in a custom struct
.
But as you said, it would be nice if each reference was removed from the dictionary immediately after it died. I think the only way to do this is to somehow use finalizers. But if you don't want to (or can't) modify the type in the dictionary, this will get quite complicated.
The basic idea is that you will have the same dictionary of weak references as above (the caveats about how to remove items still apply), but you also attach a helper object with a finalizer to each item in the dictionary using ConditionalWeakTable
. And in that finalizer, you will remove the item from the dictionary. Because of how ConditionalWeakTable
works, if an item in the dictionary gets GCed, the attached object will too, which means its finalizer will be called and so the item will be removed from the dictionary