title: Is the following thread safe?
body: <p>I have the following code and wonder whether it is thread safe. I only lock when I add or remove items from the collection but do not lock when I iterate over the collection. Locking while iterating would severely impact performance because the collection potentially contains hundreds of thousands of items. Any advice what to do to make this thread safe? </p>
  
  <p>Thanks</p>
  
  <pre><code>public class Item
  {
      public string DataPoint { get; private set; }
  
      public Item(string dataPoint)
      {
          DataPoint = dataPoint;
      }
  }
  
  public class Test
  {
      private List&lt;Item&gt; _items; 
      private readonly object myListLock = new object();
  
      public Test()
      {
          _items = new List&lt;Item&gt;();
      }
  
      public void Subscribe(Item item)
      {
          lock (myListLock)
          {
              if (!_items.Contains(item))
              {
                  _items.Add(item);
              }
          }
      }
  
      public void Unsubscribe(Item item)
      {
          lock (myListLock)
          {
              if (_items.Contains(item))
              {
                  _items.Remove(item);
              }
          }
      }
  
      public void Iterate()
      {
          foreach (var item in _items)
          {
              var dp = item.DataPoint;
          }
      }
  
  }
  </code></pre>
  
  <p><strong>EDIT</strong></p>
  
  <p>I was curious and again profiled performance between an iteration that is not locked vs iterating inside the lock on the <code>myListLock</code> and the performance overhead of locking the iteration over 10 million items was actually quite minimal. </p>