Collection was modified; enumeration operation may not execute

后端 未结 16 2581
南旧
南旧 2020-11-21 06:05

I can\'t get to the bottom of this error, because when the debugger is attached, it does not seem to occur.

Collection was modified; enumeration operatio

相关标签:
16条回答
  • 2020-11-21 07:02

    You can copy subscribers dictionary object to a same type of temporary dictionary object and then iterate the temporary dictionary object using foreach loop.

    0 讨论(0)
  • 2020-11-21 07:04

    What's likely happening is that SignalData is indirectly changing the subscribers dictionary under the hood during the loop and leading to that message. You can verify this by changing

    foreach(Subscriber s in subscribers.Values)
    

    To

    foreach(Subscriber s in subscribers.Values.ToList())
    

    If I'm right, the problem will disappear.

    Calling subscribers.Values.ToList() copies the values of subscribers.Values to a separate list at the start of the foreach. Nothing else has access to this list (it doesn't even have a variable name!), so nothing can modify it inside the loop.

    0 讨论(0)
  • 2020-11-21 07:04

    You can also lock your subscribers dictionary to prevent it from being modified whenever its being looped:

     lock (subscribers)
     {
             foreach (var subscriber in subscribers)
             {
                   //do something
             }
     }
    
    0 讨论(0)
  • 2020-11-21 07:04

    I had the same issue, and it was solved when I used a for loop instead of foreach.

    // foreach (var item in itemsToBeLast)
    for (int i = 0; i < itemsToBeLast.Count; i++)
    {
        var matchingItem = itemsToBeLast.FirstOrDefault(item => item.Detach);
    
       if (matchingItem != null)
       {
          itemsToBeLast.Remove(matchingItem);
          continue;
       }
       allItems.Add(itemsToBeLast[i]);// (attachDetachItem);
    }
    
    0 讨论(0)
提交回复
热议问题