System.InvalidOperationException: Collection was modified

前端 未结 6 1272
花落未央
花落未央 2020-11-30 15:05

I am getting a following exception while enumerating through a queue:

System.InvalidOperationException: Collection was modified; enumeration opera

6条回答
  •  余生分开走
    2020-11-30 15:36

    You are allowed to change the value in an item in a collection. The error you're getting means that an item was either added or removed i.e.: the collection itself was modified, not an item inside the collection. This is most likely caused by another thread adding or removing items to this collection.

    You should lock your queue at the beginning of your method, to prevent other Threads modifying the collection while you are accessing it. Or you could lock the collection before even calling this method.

    private bool extractWriteActions(out List channelWrites)
        {
          lock(tpotActionQueue)
          {
            channelWrites = new List();
            foreach (TpotAction action in tpotActionQueue)
            {
                if (action is WriteChannel)
                {
                    channelWrites.Add((WriteChannel)action);
    
                      action.Status = RecordStatus.Batched;
    
               }
            }
          }
           return (channelWrites.Count > 0);
       }
    

提交回复
热议问题