0

I have two static procedures in one class that are called at various points during real time.

Both procedures access the same list. One adds to the list, the other removes items from the list.

The problem is that they are both conflicting with each other and I repeatedly receive the message:

"Collection was modified; enumeration operation may not execute"

Forgive my ignorance. But I believe I need to lock the collection somehow, whilst one task is working on it. But I also want the other process to immediate take over once the other task has finished.

Thanks in advance

hearme
  • 1
  • 1
  • We already have lots of Q&A on Stack Overflow addressing the exception you're seeing. Note that this really has nothing to do with the multi-threading aspect, except inasmuch as you could take a lock for the entire duration of the enumeration, and also take the same lock while trying to modify the list, to ensure mutual exclusion. If you are implementing producer/consumer and you want to enumerate the list all at once, you should just copy the list and then clear the original. Better approaches involve using `Queue` or `BlockingCollection` (which has synchronization built-in). – Peter Duniho Jul 12 '17 at 22:45
  • Can you provide another article to assist, the above explanation didn't explain it in enough detail for myself :/ – hearme Jul 12 '17 at 22:51
  • [_"If changes are made to the collection, such as adding, modifying, or deleting elements, the enumerator is irrecoverably invalidated and its behavior is undefined."_](https://msdn.microsoft.com/en-us/library/b0yss765(v=vs.110).aspx) I don't if that would actually help you that much either, if the discussion already referenced did not. I recommend you copy and paste the error message text into the Stack Overflow search or your favorite web search. – Peter Duniho Jul 12 '17 at 23:10
  • The bottom line is you aren't allowed to modify a collection while using an enumerator for that collection. How to fix it depends entirely on what your exact code looks like, which you haven't shared. If after reviewing the available information you still can't figure it out, post a new question but this time make sure you include a good [mcve], along with an explanation of what you've done so far to try to solve the problem and what _specifically_ you're still having trouble with. – Peter Duniho Jul 12 '17 at 23:10

0 Answers0