title: Multiple threads modifying a collection
body: <p>I'm trying to learn about threads for an assignment for school, and I'm trying to get two threads to empty a collection. The code I came up with so far throws an exception, saying that the collection got modified.</p>
  
  <p>First I had a while loop in the locked code part, but then (of course ;-)) only one thread empties the collection.</p>
  
  <p>My question is, how can I have a loop in which the threads both take turns in emptying the collection?</p>
  
  <pre><code>class Program
  {
      private static List&lt;int&gt; containers = new List&lt;int&gt;();
  
      static void Main(string[] args)
      {
          for (int i = 0; i &lt; 100; i++)
          {
              containers.Add(i);
          }
  
          Thread t1 = new Thread(() =&gt; { foreach (int container in containers) { GeefContainer(); } });
          t1.Name = "Kraan 1";
          t1.Start();
  
          Thread t2 = new Thread(() =&gt; { foreach (int container in containers) { GeefContainer(); } });
          t2.Name = "Kraan 2";
          t2.Start();
  
          Console.Write("Press any key to continue...");
          Console.Read();
      }
  
      static void GeefContainer()
      {
          lock (containers)
          {
              int containerNummer = containers.Count - 1;
  
              //Container container = containers[containerNummer];
  
              //Console.Write("Container {0} opgehaald... Overladen", containerNummer);
              Console.WriteLine("Schip: Container {0} gegeven aan {1}", containerNummer, Thread.CurrentThread.Name);
  
              //Gevaarlijk, want methode aanroepen kan klappen
              containers.RemoveAt(containerNummer);
          }
      }
  }
  </code></pre>