title: What collection to use in an multi-threaded observer pattern?
body: <p>I am currently implementing a Observer design situation.</p>
  
  <p>I have my list of registered observers in my main class.</p>
  
  <pre><code>private static volatile List&lt;IObserver&gt; registeredObservers;
  </code></pre>
  
  <p>Each Observer is a network socket, when the socket is connected and all is good, it registers its self with the observable class. If there is an error or the socket simply disconnects it then de-registers / removes its self from the observable.</p>
  
  <p>This all seems to work well and good. I am happy.</p>
  
  <p>but now in my main class I loop through all the registered observers as below:</p>
  
  <pre><code>private void SendEventToObservers(ILogItem item)
  {
      foreach (var observer in registeredObservers)
      {
          if (observer != null)
          {
              observer.OnMessageRecieveEvent(new ObserverEvent(item));
          }
      }
  }
  </code></pre>
  
  <p>This then throws the following error:</p>
  
  <pre><code>Collection was modified; enumeration operation may not execute
  </code></pre>
  
  <p>Now I have read in another SO thread that I need to change the for each to add the .ToList() :</p>
  
  <pre><code>foreach (var observer in registeredObservers.ToList()) 
  </code></pre>
  
  <p>Now this doesn't quite solve my issue, because if an Observer removes its self from the list while it is busy looping though, the .toList() creates an "old" representation of the list?</p>
  
  <p>I was thinking would there not be a better sort of concurrent list which can block when being accessed and when observers are being added and removed?</p>
  
  <p>Or will the current .ToList() Solution work?</p>