1

Possible Duplicate:
Collection was modified; enumeration operation may not execute

I have a generic List where I execute some actions while enumerating.

foreach(Action<string> action in actionList) 
{
    if(action != null) {
        action(mystring);
    }
}

Now I get this exception:

InvalidOperationException:
Collection was modified; enumeration operation may not execute

How can this be solved, I am nailed tight to .NET 3.5 :/

Community
  • 1
  • 1
Pascal
  • 12,265
  • 25
  • 103
  • 195

2 Answers2

6

Well presumably one of the actions modifies actionList, invalidating the iterator. The simplest way to avoid the error is to take a copy of the list first, e.g.

foreach(Action<string> action in actionList.ToList()) 
{
    if(action != null) {
        action(mystring);                               
    }
}

Or even:

foreach (var action in actionList.Where(action => action != null).ToList())
{
    action(mystring);
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • +1. answer in less than 1min :) – Renatas M. Apr 19 '12 at 11:31
  • I tried your first code snippet which throws a NullRefException :( – Pascal Apr 19 '12 at 11:37
  • @Pascal: It shouldn't... where did it throw an exception? I assume `actionList` itself is non-null? A short but complete program demonstrating the problem would really help... – Jon Skeet Apr 19 '12 at 12:17
  • The exception I get in a third party assembly. – Pascal Apr 19 '12 at 13:07
  • @Pascal: Then presumably it's a bug somewhere in that, or in how you're using it... but there's no way of me fixing that in the code you're giving here. That's a completely separate problem to the one you've given in this question. – Jon Skeet Apr 19 '12 at 13:41
0

You modified the actionList during the iteration on it. It could be a second thread which is not synchronized with a current loop or the action method which make the modification or another iteration. So the solution could be:

var tmp = new List<Action<string> >(actionList);
foreach(Action<string> action in tmp) 
{
    if(action != null) {
      action(mystring);                               
    }
}

But it will work only in case of action's modification in case of a parallel thread you should synchronize the list.

AlexTheo
  • 4,004
  • 1
  • 21
  • 35
  • same as Skeets answer => NullRefException – Pascal Apr 19 '12 at 11:39
  • I know I wrote it while Skeets posted his answer, so should I delete it? Also there is mentioned that the problem could come in the multithreaded environment. – AlexTheo Apr 19 '12 at 11:42