从ConcurrentDictionary中删除多个元素

时间:2019-12-12 14:42:29

标签: c# asp.net

我有以下代码:

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 ??
            }
        }
    }

谢谢

1 个答案:

答案 0 :(得分:1)

编辑:删除了误导性代码更改。

由于它是import GetLocation from 'react-native-get-location' GetLocation.getCurrentPosition({ enableHighAccuracy: true, timeout: 15000, }) .then(location => { console.log(location); }) .catch(error => { const { code, message } = error; console.warn(code, message); }) ,所以集合本身已经解决了竞争条件。此外,如果在foreach循环中进行修改,它也不会遭受可怕的“枚举时修改了集合”错误。

相关问题