ConcurrentDictionary的乐观并发Remove方法
我正在 ConcurrentDictionary 中寻找一种方法,当且仅当该值等于我指定的值时,它允许我通过键删除条目,类似于 TryUpdate 的等效项,但用于删除。
执行此操作的唯一方法似乎是此方法:
ICollection<KeyValuePair<K, V>>.Remove(KeyValuePair<K, V> keyValuePair)
它是 ICollection 接口的显式实现,换句话说,我必须首先将 ConcurrentDictionary 转换为 ICollection,以便我可以调用Remove。
Remove 正是我想要的,而且那个强制转换也没什么大不了的,而且源代码显示它使用 bool matchValue = true 调用私有方法 TryRemovalInternal,所以一切看起来都很好很干净。
然而,让我有点担心的是,它没有被记录为 ConcurrentDictionary 的乐观并发删除方法,因此 http://msdn.microsoft.com/en-us/library/dd287153.aspx 只是复制 ICollection 样板,并且 如何:从 ConcurrentDictionary 添加和删除项目 也没有提及该方法。
有谁知道这是否是正确的方法,或者我还缺少其他方法吗?
I was looking for a method in ConcurrentDictionary that allows me to remove an entry by key, if and only if the value is equal to one that I specify, something like the equivalent of TryUpdate, but for removals.
The only method that does this seems to be this method:
ICollection<KeyValuePair<K, V>>.Remove(KeyValuePair<K, V> keyValuePair)
It is the explicit implementation of the ICollection interface, in other words, I have to cast my ConcurrentDictionary to an ICollection first so that I can call Remove.
Remove does exactly what I want, and that cast is no big deal either, also the source code shows it calls the private method TryRemovalInternal with bool matchValue = true, so it all looks nice and clean.
What worries me a bit however is the fact that it is not documented as the optimistically concurrent Remove method of ConcurrentDictionary, so http://msdn.microsoft.com/en-us/library/dd287153.aspx just duplicates the ICollection boilerplate, and the How to: Add and Remove Items from a ConcurrentDictionary does not mention that method either.
Does anyone know if that's the way to go, or is there some other method that I'm missing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
虽然它不是官方文档,但此MSDN 博客文章 可能会有所帮助。该文章的要点:转换为
ICollection
并调用其Remove
方法,正如问题中所述,是正确的方法。以下是上述博客文章的片段,它将其包装到
TryRemove
扩展方法中:Though it is not an official document, this MSDN blog post can be helpful. The gist of that article: casting to
ICollection
and calling itsRemove
method, just as described in the question, is the way to go.Here's a snippet from the above blog post, which wraps it into a
TryRemove
extension methods:如果您不需要所有的铃声和铃声; ConcurrentDictionary 的口哨声,您可以将您的类型声明为 IDictionary。
我发现这在您只需要添加和删除但仍然想要线程安全迭代的情况下很有用。
If you don't need all the bells & whistles of ConcurrentDictionary, you can just declare your type as an IDictionary.
I find this useful in situation in which you only need to add and remove, but still want a thread-safe iteration.