title: Fastest and still safe way to exchange reference variables values
body: <p>Basically what i need is to be able to add items to List (or another collection) constantly, around 3000 times per second in one thread. And to get and remove all items from that list once per 2 seconds. </p>
  
  <p>I don't like classic ways to do this like using concurrent collections or lock on something every time i need to access collection because it would be slower than i need.</p>
  
  <p>What i'm trying to do is to have 2 collections, one for each thread, and to find a way to make a thread safe switch from one collection to another.</p>
  
  <p><strong>Simplified</strong> and not thread-safe example:</p>
  
  <pre><code>var listA = new List&lt;int&gt;();
  var listB = new List&lt;int&gt;();
  
  // method is called externally 3000 times per second
  void ProducerThread(int a)
  {      
      listA.Add(a)      
  }
  void ConsumerThread()
  {
    while(true)
    {
      Thread.Sleep(2000);
      listB = Interlocked.Exchange(ref listA,listB);
      //... processing listB data
      // at this point when i'm done reading data
      // producer stil may add an item because ListA.Add is not atomic
      // correct me if i'm wrong
      listB.Clear();
    }
  }
  </code></pre>
  
  <p>Is there any way to make above code work as intended (to be thread safe) while having producer thread blocked as little as possible? Or maybe another solution?</p>