是否有可能建立在C#中忠实地弱密钥的字典吗? [英] Is it possible to create a truely weak-keyed dictionary in C#?
问题描述
我想螺母的细节一个真正的 WeakKeyedDictionary<,>
的C#...但我遇到困难
我意识到这是一个不平凡的任务,但似乎没有能力来声明 WeakKeyedKeyValuePair<,>
(其中GC只有遵循的价值基准,如果关键可达),使得它看起来不可能。
有两个主要的问题,我看到的:
-
到目前为止,我所看到的每一个执行不剪裁值键已收集后。想想 - 对使用这样的字典的主要原因之一是prevent被保留这些值各地(不仅仅是钥匙!),因为它们是无法访问的,但在这里,他们留下指向强引用<。 / P>
是的,添加/从字典中删除足够的,他们最终会被取代,但如果你不这样做?
-
如果没有一个假设
WeakKeyedKeyValuePair&LT;,&GT;
(或告诉GC只标出值,如果关键是可达的另一种方式)的任何值,是指它的键永远不会被收集。这是存储任意值,当出现问题。
1的问题可以解决在一个相当不理想/ hackish的方法:用GC通知等待一个完整的GC完成,然后一起去剪枝字典在另一个线程。这一次我是半确定与
但问题2有我难住了。我意识到这是很容易被所以不要做反驳,但它有我疑惑 - 这方面的问题,甚至可能解决
有一个看 ConditionalWeakTable&LT; TKEY的,TValue&GT;类。
使编译器动态附加对象字段被管理对象。
它本质上是一本字典,其中两个键和值是 WeakReference的,且该值被保持活只要键是活的。
请注意!此类不使用 GetHash code
和等于
做相等比较,它使用了的ReferenceEquals
。
I'm trying to nut out the details for a true WeakKeyedDictionary<,>
for C#... but I'm running into difficulties.
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:
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?
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.
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.
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?
Have a look at the ConditionalWeakTable<TKey, TValue> Class.
Enables compilers to dynamically attach object fields to managed objects.
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.
Note! This class does not use GetHashCode
and Equals
to do equality comparisons, it uses ReferenceEquals
.
这篇关于是否有可能建立在C#中忠实地弱密钥的字典吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!