7

我在 ConcurrentDictionary 中寻找一种方法,当且仅当值等于我指定的值时,它允许我通过键删除条目,类似于TryUpdate的等价物,但用于删除。

这样做的唯一方法似乎是这种方法:

ICollection<KeyValuePair<K, V>>.Remove(KeyValuePair<K, V> keyValuePair)

它是 ICollection 接口的显式实现,换句话说,我必须先将我的 ConcurrentDictionary 转换为 ICollection,这样我才能调用 Remove。

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也没有提到该方法。

有谁知道这是要走的路,还是我缺少其他方法?

4

2 回答 2

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));
}
于 2012-01-04T14:50:35.857 回答
0

如果您不需要 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");
    }
}

我发现这在您只需要添加和删除但仍需要线程安全迭代的情况下很有用。

于 2013-11-30T16:48:47.073 回答