C# – System.InvalidOperationException: Collection was modified

c++collectionsthread-safety

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

System.InvalidOperationException:
Collection was modified; enumeration
operation may not execute

here is the code excerpt:

1:    private bool extractWriteActions(out List<WriteChannel> channelWrites)
2:    {
3:        channelWrites = new List<WriteChannel>();
4:        foreach (TpotAction action in tpotActionQueue)
5:        {
6:            if (action is WriteChannel)
7:            {
8:                channelWrites.Add((WriteChannel)action);
9:                lock(tpotActionQueue)
10:               {
11:                  action.Status = RecordStatus.Batched;
12:               }
13:           }
14:       }
15:       return (channelWrites.Count > 0);
16:   }

I think I understand the problem – altering the hashtable at action.Status = RecordStatus.Batched, which screws up the MoveNext() on enumerator.
Question is, how do I implement that "pattern" correctly?

Best Solution

I think I had a similar exception when using a foreach loop on a Collection where I tried to remove items from the Collection (or it may have been a List, I can't remember). I ended up getting around it by using a for loop. Perhaps try something like the following:

for (int i=0; i<tpotActionQueue.Count(); i++)
{
    TpotAction action = tpotActionQueue.Dequeue();
    if (action is WriteChannel)
    {
        channelWrites.Add((WriteChannel)action);
        lock(tpotActionQueue)
        {
            action.Status = RecordStatus.Batched;
        }
    }
}
Related Question