tabs ↹ over ␣ ␣ ␣ spaces

by Jiří {x2} Činčura

Count for System.Collections.Concurrent.ConcurrentStack<T>

17 Apr 2012 .NET, Best practice or not?, Multithreading/Parallelism/Asynchronous/Concurrency

Collections in System.Collections.Concurrent namespace are optimized for access from more (basically) threads. That means no stupid “one-lock-for-everything” approach. Actually these are lock free.

It’s good for performance, but also, if used foolhardily, the performance penalty can be too big. One example can be the ConcurrentStack<T> class. As with a lot of collections, this stack also has a Count property. But because it’s a lock free implementation using linked list the Count isn’t that easy. Actually it’s O(n) and this can be especially bad for big stacks. So use with care. As the remarks for this property recommends, if you need to know just whether it’s empty of not, the IsEmpty is better (though realize, that in time you check it it might be empty, but not on next line where you’re about to perform some action and vice versa).

Use the tools, but also know your tools.