问题描述
我正在尝试为 C# 编写一个真正的 WeakKeyedDictionary<,>
的详细信息...但我遇到了困难.
I'm trying to nut out the details for a true WeakKeyedDictionary<,>
for C#... but I'm running into difficulties.
我意识到这是一项不平凡的任务,但似乎无法声明 WeakKeyedKeyValuePair<,>
(其中 GC 仅在键可访问时遵循值引用)使它看起来不可能.
I realise this is a non-trivial task, but the seeming inability to declare a WeakKeyedKeyValuePair<,>
(where the GC only follows the value reference if the key is reachable) makes it seemingly impossible.
我看到了两个主要问题:
There are two main problems I see:
到目前为止,我看到的每个实现都不会在收集键后修剪值.想想看 - 使用这样一个 Dictionary 的主要原因之一是防止这些值被保留(不仅仅是键!),因为它们无法访问,但在这里它们被强引用指向.
Every implementation I've so far seen does not trim values after keys have been collected. Think about that - one of the main reasons for using such a Dictionary is to prevent those values being kept around (not just the keys!) as they're unreachable, but here they are left pointed to by strong references.
是的,从字典中添加/删除足够多,它们最终会被替换,但如果你不这样做呢?
Yes, add/remove from the Dictionary enough and they'll eventually be replaced, but what if you don't?
如果没有假设的 WeakKeyedKeyValuePair
WeakKeyedKeyValuePair<,>
(或另一种告诉 GC 仅在键可访问时标记值的方法),任何引用它的键的值都不会集.这是存储任意值时的问题.
Without a hypothetical WeakKeyedKeyValuePair<,>
(or another means of telling the GC to only mark the value if the key is reachable) any value that refers to it's key would never be collected. This is a problem when storing arbitrary values.
问题 1 可以通过一种相当不理想/骇人听闻的方式解决:使用 GC 通知等待完整的 GC 完成,然后继续在另一个线程中修剪字典.这个我还可以.
Problem 1 could be tackled in a fairly non-ideal/hackish way : use GC Notifications to wait for a full GC to complete, and then go along and prune the dictionary in another thread. This one I'm semi-ok with.
但问题 2 让我很困惑.我意识到这很容易被所以不要那样做"所反驳,但这让我想知道 - 这个问题甚至可以解决吗?
But problem 2 has me stumped. I realise this is easily countered by a "so don't do that", but it has me wondering - is this problem even possible to solve?
推荐答案
看看 ConditionalWeakTable
使编译器能够将对象字段动态附加到托管对象.
Enables compilers to dynamically attach object fields to managed objects.
它本质上是一个字典,其中键和值都是 WeakReference,只要 key 存在,value 就会保持活跃.
It's essentially a dictionary where both the key and the value are a WeakReference, and the value is kept alive as long as the key is alive.
注意!这个类不使用GetHashCode
和Equals
做相等比较,它使用ReferenceEquals
.
Note! This class does not use GetHashCode
and Equals
to do equality comparisons, it uses ReferenceEquals
.
这篇关于是否可以在 C# 中创建一个真正的弱键字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!