.net ConcurrentDictionary';s最优并行删除方法
我在ConcurrentDictionary中寻找一种方法,该方法允许我按键删除条目,当且仅当值等于我指定的值时(类似于TryUpdate),但用于删除 唯一能做到这一点的方法似乎是这种方法:.net ConcurrentDictionary';s最优并行删除方法,.net,optimistic-concurrency,.net,Optimistic Concurrency,我在ConcurrentDictionary中寻找一种方法,该方法允许我按键删除条目,当且仅当值等于我指定的值时(类似于TryUpdate),但用于删除 唯一能做到这一点的方法似乎是这种方法: ICollection<KeyValuePair<K, V>>.Remove(KeyValuePair<K, V> keyValuePair) ICollection.Remove(KeyValuePair KeyValuePair) 这是ICollection接口
ICollection<KeyValuePair<K, V>>.Remove(KeyValuePair<K, V> keyValuePair)
ICollection.Remove(KeyValuePair KeyValuePair)
这是ICollection接口的显式实现,换句话说,我必须首先将ConcurrentDictionary转换为ICollection,以便调用Remove
Remove做的正是我想要的,cast也没什么大不了的,而且源代码显示它调用私有方法TryRemovalInternal,bool matchValue=true,所以看起来很好,很干净
然而,让我有点担心的是,它并没有被记录为ConcurrentDictionary的乐观并发删除方法,所以只是复制了ICollection样板文件,而且也没有提到该方法
有人知道这是一条路吗?或者我还缺少其他方法吗?虽然这不是一份正式文件,但可能会有所帮助。这篇文章的要点是:如问题中所述,强制转换到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));
}
公共静态bool TryRemove(
此ConcurrentDictionary(字典、TKey键、TValue值)
{
if(dictionary==null)
抛出新的ArgumentNullException(“字典”);
返回((ICollection)字典)。删除(
新的KeyValuePair(键,值));
}
如果您不需要ConcurrentDictionary的所有功能,只需将您的类型声明为IDictionary即可
public class ClassThatNeedsDictionary
{
private readonly IDictionary<string, string> storage;
public ClassThatNeedsDictionary()
{
storage = new ConcurrentDictionary<string, string>();
}
public void TheMethod()
{
//still thread-safe
this.storage.Add("key", "value");
this.storage.Remove("key");
}
}
public类需要索引的类
{
专用只读词典存储器;
需要字典()的公共类
{
存储=新的ConcurrentDictionary();
}
公共无效方法()
{
//仍然线程安全
此项。存储。添加(“键”、“值”);
此。存储。删除(“密钥”);
}
}
我发现这在您只需要添加和删除,但仍然需要线程安全的迭代的情况下很有用。看起来不错(因为它与
TryRemove
调用的方法相同,只是matchValue
设置为false和oldValue
默认值),尽管它不是官方文档,这可能会很有帮助:@alexm这已经足够让人放心了-如果你把它变成一个答案,我会接受的!MS真的应该更新他们的文档,如果他们最近真的“看到一些人要求ConcurrentDictionary提供进一步的支持”…如果在某些情况下,您使用ConcDic,但不需要它的专门方法,我没有遇到它们。但如果有,你的建议肯定会让演员阵容变得多余。Otoh,我很确定这是一个“编译时强制转换”,所以没有任何性能损失。只是有点难看的代码。在需要在迭代字典的同时从字典中添加和删除对象的场景中。因为ConcurrentDictionary提供了一个密钥快照,所以不会出现异常。