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