title: Collection was modified; enumeration operation may not execute. C#
body: <p>I need help. I am working with an arraylist, and suddenly I get this error.</p>
  
  <blockquote>
    <p>An unhandled exception of type 'System.InvalidOperationException' occurred in mscorlib.dll</p>
    
    <p>Additional information: Collection was modified; enumeration operation may not execute.</p>
  </blockquote>
  
  <p>This is the code where it shows the exception...</p>
  
  <pre><code>foreach (PC_list x in onlinelist) {
    if ((nowtime.Subtract(x.time)).TotalSeconds &gt; 5) {
      Invoke(new MethodInvoker(delegate {
        index = Main_ListBox.FindString(x.PcName);
        if(index != ListBox.NoMatches)
        Main_ListBox.Items.RemoveAt(index);
      }));
      onlinelist.Remove(x);
      //Thread.Sleep(500);
    }
  }
  </code></pre>
  
  <p>Where</p>
  
  <pre><code>public class PC_list {
      public string PcName;
      public string ip;
      public string status;
      public string NickName;
      public DateTime time;
  
  }
  </code></pre>
  
  <p><em>Notes:</em></p>
  
  <ul>
  <li>onlinelist is an arraylist</li>
  <li>nowtime and x.time are DateTime.</li>
  </ul>
  
  <p><strong>Call Stack</strong></p>
  
  <pre><code>mscorlib.dll!System.Collections.ArrayList.ArrayListEnumeratorSimple.MoveNext() + 0x122 bytes    
  BlueBall.exe!BlueBall.BlueBall.clean_arraylist() Line 74 + 0x1a8 bytes  C#
  BlueBall.exe!BlueBall.BlueBall.server() Line 61 + 0x8 bytes C#
  mscorlib.dll!System.Threading.ThreadHelper.ThreadStart_Context(object state) + 0x63 bytes   
  mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool ignoreSyncCtx) + 0xb0 bytes    
  mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state) + 0x2c bytes    
  mscorlib.dll!System.Threading.ThreadHelper.ThreadStart() + 0x44 bytes   
  [Native to Managed Transition]
  </code></pre>