title: Why does ConcurrentWhatever.Count take a snapshot
body: <p>On <a href="http://geekswithblogs.net/BlackRabbitCoder/archive/2011/02/10/c.net-little-wonders-the-concurrent-collections-1-of-3.aspx" rel="noreferrer">C#/.NET Little Wonders article for ConcurrentStack / Concurrent Queue</a>, the following is mentioned regarding the <code>.Count</code> operation on the <code>ConcurrentStack</code>:</p>
  
  <blockquote>
    <p>Count takes a snapshot of the stack
    and then counts the items. This means
    it is a O(n) operation, if you just
    want to check for an empty stack, call
    IsEmpty instead which is O(1).</p>
  </blockquote>
  
  <p>I'm not greatly experienced in multi-threaded programming yet, but I understand why you can't just loop through the items on the collection and count them, because the collection may be changing by other threads at the same time.  However, if you have to lock the  <code>ConcurrentStack</code> long enough to make a snapshot, wouldn't it be easier just to count the items while you have it locked, return that count, and release the lock, instead of  taking the overhead and time cost of generating an entire snapshot before releasing the lock?</p>
  
  <p>I may be missing something basic about how this works, and I would appreciate any thoughts or insight you may have.</p>