title: Standard solution for asynch call interfering with collection during loop?
body: <p>I'm working on a program, in c# that uses asynchronous network calls. Some of these modify a collection the rest of the program loops through from time to time. The problem is that when the asynchronous call is trying to modify to collection during the loop an exception is thrown and the program crashes.</p>
  
  <p>I'm fairly new to this type of programming and this seems like a common problem that should have a standard solution.</p>
  
  <p>What I tried was to set up a bool that I switch off before looping through the collection and check in the asynchronous method. If it is not on I modify a different collection, and make the changes based on that to the original in the rest of the program. The problem is that the asynchronous method also has a loop over this collection, so when it is called in succession quickly it can interfere with that loop.</p>
  
  <p>I figure a better solution would be to set up the code so that while the bool denoting that the collection is not safe to modify is true, any of these calls are delayed. However I don't know if this is a good enough solution (since I figure that the asynchronous call could first begin, then the program could get to the unsafe part).</p>
  
  <p>This is not the actual program, but an example of the problem for clarity:</p>
  
  <pre><code> private List&lt;Stuff&gt; myList = new List();
  
   private void NetworkDataReceived(Stuff s)
   {
     myList.Add(s);
   }
  
   private void SomeOtherMethod()
   {
     foreach(Stuff s in myList)
     {
       DoSomethingWithStuff(s);
     }
   }
  </code></pre>
  
  <p>In the example above when NetworkDataReceived is called while SomeOtherMethod is also running, the program crashes with the following InvalidOperationException: "Collection was modified; enumeration operation may not execute."</p>
  
  <p>I'd appreciate it if somebody who has experience in this kind of programming in C# could give me a pointer to how to resolve this issue.</p>