ConcurrentDictionary的乐观并发Remove方法

Eug*_*sky 7 .net optimistic-concurrency

我在ConcurrentDictionary中寻找一个方法,允许我按键删除一个条目,当且仅当该值等于我指定的值时,类似于TryUpdate,但是对于删除.

执行此操作的唯一方法似乎是此方法:

ICollection<KeyValuePair<K, V>>.Remove(KeyValuePair<K, V> keyValuePair)
Run Code Online (Sandbox Code Playgroud)

它是ICollection接口的显式实现,换句话说,我必须首先将ConcurrentDictionary转换为ICollection,以便我可以调用Remove.

删除完全符合我的要求,并且该投射也没什么大不了的,源代码也显示它调用私有方法TryRemovalInternal与bool matchValue = true,所以它看起来都很漂亮和干净.

然而,令我担心的是,它没有被记录为ConcurrentDictionary的乐观并发Remove方法,因此http://msdn.microsoft.com/en-us/library/dd287153.aspx只是重复ICollection样板,并且该如何从一个ConcurrentDictionary添加和删除的项目并不要么提到的方法.

有谁知道这是否可行,或者是否有其他方法我缺席?

ale*_*exm 5

尽管它不是正式文档,但该MSDN博客文章可能会有所帮助。该文章的要旨是:如问题中所述,强制转换ICollection并调用其Remove方法。

这是上述博客文章的摘录,将其包装为TryRemove扩展方法:

public static bool TryRemove<TKey, TValue>(
    this ConcurrentDictionary<TKey, TValue> dictionary, TKey key, TValue value)
{
    if (dictionary == null)
      throw new ArgumentNullException("dictionary");
    return ((ICollection<KeyValuePair<TKey, TValue>>)dictionary).Remove(
        new KeyValuePair<TKey, TValue>(key, value));
}
Run Code Online (Sandbox Code Playgroud)