从ConcurrentDictionary中删除多个元素

问题描述 投票:0回答:1

我有以下代码:

public class Item
{
   public string key { get; set; }
   public string Value { get; set; }
}

private ConcurrentDictionary<string, string> StorageItems { get; set; }

private void Reload(IEnumerable<Item> newItems)
{
  foreach (Item item in newItems)
    {
      StorageItems.AddOrUpdate(item.key, item.Value, (s, o) => item.Value);
    }

 // TODO remove from StorageItems the items that newItems does not contains
 }

我有以下想法,但是我不确定要从循环体内的ConcurrentDictionary中删除元素:

private void ReloadIdea(IEnumerable<Item> newItems)
    {
        List<string> addedOrUpdatedKeys = new List<string>();

        foreach (Item item in newItems)
        {
            StorageItems.AddOrUpdate(item.key, item.Value, (s, o) => item.Value);

            addedOrUpdatedKeys.Add(item.key);
        }

        foreach (string key in StorageItems.Keys)
        {
            if (!addedOrUpdatedKeys.Contains(key))
            {
                string removedValue;

                StorageItems.TryRemove(key, out removedValue); // <-- Removing items from collection that is iterating ??
            }
        }
    }

谢谢,

c# asp.net
1个回答
0
投票

您无需明确检查字典是否包含要删除的项目。 TryRemove将自动为您执行此操作。

因为它是ConcurrentDictionary,所以比赛条件已经由集合本身解决了。此外,如果您在foreach循环中对其进行修改,它不会遭受可怕的“枚举时修改了集合”错误。

private void ReloadIdea(IEnumerable<Item> newItems)
{
    List<string> addedOrUpdatedKeys = new List<string>();

    foreach (Item item in newItems)
    {
        StorageItems.AddOrUpdate(item.key, item.Value, (s, o) => item.Value);

        addedOrUpdatedKeys.Add(item.key);
    }

    foreach (string key in StorageItems.Keys)
    {
        StorageItems.TryRemove(key, out var removedValue); // This is perfectly fine for a ConcurrentDictionary.
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.