title: C# list concurrency
body: <p>I'm working on a simple irc chat bot (specifically for twitch.tv streams), and I'm using a List to keep a list of all the users in the channel.  When someone leaves or joins, I add or remove them from the list.  Then I have a thread that runs every minute that checks if the stream is online, and if it is, it hands out "currency" to all the people in my user list.</p>
  
  <p>I'm sure you can already see where my problem is.  If someone leaves or joins while my program is looping through the users in my list, then I get a Collection Modified exception.  Currently, as a workaround, I just make a temp list and copy the real list into it, then loop through the temp list instead, but I was just curious if there was a "better" way to do it?</p>
  
  <p>Quick psuedocode:</p>
  
  <pre><code>private List&lt;string&gt; users = new List&lt;string&gt;();
  
  private void IrcInitialize(){
      //connect to irc stuff
      //blah
      //blah
      //blah
      Thread workThread = new Thread(new ThreadStart(doWork());
      workThread.Start();
  }
  
  private void ircListener(){
      parseIRCMessage(StreamReader.ReadLine());
  }
  
  private void parseIRCMessage(msg){
      if (msgType == "JOIN"){
          users.Add(user);
      }
      else if (msgType == "PART"){
          users.Remove(user);
      }
  }
  
  private void doWork(){
      while (true) {
          if (streamOnline() &amp;&amp; handOutTime()){
              handOutCurrency();
          }
          Thread.Sleep(60000);
      }
  }
  
  private void handOutCurrency(){
      List&lt;string&gt; temp = users; //This is what I'm currently doing
      foreach (String user in temp) {
          database.AddCurrency(user, 1);
      }
  }
  </code></pre>
  
  <p>Any other suggestions?</p>