ConcurrentDictionary's optimistically concurrent Remove
本文关键字:optimistically concurrent Remove ConcurrentDictionary | 更新日期: 2023-09-27 18:19:19
我正在ConcurrentDictionary中寻找一个方法,该方法允许我按键删除条目,当且仅当值等于我指定的值,类似于TryUpdate的等效,但用于删除。
唯一这样做的方法似乎是这个方法:
ICollection<KeyValuePair<K, V>>.Remove(KeyValuePair<K, V> keyValuePair)
它是ICollection接口的显式实现,换句话说,我必须首先将我的ConcurrentDictionary转换为ICollection,以便我可以调用Remove。
Remove做的正是我想要的,并且这种类型转换也没什么大不了的,源代码也显示它调用私有方法TryRemovalInternal与bool matchValue = true,所以它看起来很好和干净。
让我有点担心的是,它没有被记录为ConcurrentDictionary的乐观并发删除方法,所以http://msdn.microsoft.com/en-us/library/dd287153.aspx只是复制了ICollection样本,而如何:从ConcurrentDictionary中添加和删除项也没有提到该方法。
有没有人知道如果这是要走的路,或者有一些其他的方法,我错过了?
虽然这不是官方文档,但这篇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));
}
如果你不需要所有的铃铛&使用ConcurrentDictionary,你可以直接将你的类型声明为字典。
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");
}
}
我发现这在只需要添加和删除,但仍然需要线程安全迭代的情况下很有用。