.net – ConcurrentDictionary的乐观并发Remove方法
|
我在ConcurrentDictionary中寻找一个方法,它允许我按键删除一个条目,当且仅当该值等于我指定的值时,类似于TryUpdate,但是对于删除. 执行此操作的唯一方法似乎是此方法: ICollection<KeyValuePair<K,V>>.Remove(KeyValuePair<K,V> keyValuePair) 它是ICollection接口的显式实现,换句话说,我必须首先将ConcurrentDictionary转换为ICollection,以便我可以调用Remove. 删除完全符合我的要求,并且该投射也没什么大不了的,源代码也显示它调用私有方法TryRemovalInternal与bool matchValue = true,所以它看起来都很漂亮. 但令我担心的是,它没有记录为ConcurrentDictionary的乐观并发Remove方法,因此http://msdn.microsoft.com/en-us/library/dd287153.aspx只复制了ICollection样板,而How to: Add and Remove Items from a ConcurrentDictionary也没有提到该方法. 有没有人知道这是否可行,或者是否有其他方法我不知道? 解决方法虽然它不是官方文件,但 this MSDN blog post可能会有所帮助.该文章的要点:如同问题中所述,转换为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));
} (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
