Loading ...

Concurent Collections Of C

Hello everybody,

today I want to write few words about Concurent collections in C#. First of all  I want to point there there are only four of them:

  1. ConcurrentDictionary
  2. ConcurrentQueue
  3. ConcurrentStack
  4. ConcurrentBag
  5. BlockingCollection
  6. Partitioner
  7. EnumerablePartitionerOptions
  8. IProducerConsumerCollection
  9. OrderablePartitioner

Not very impressive set of collections if to compare with diversity of other collections in .Net.

Also keep in mind that ConcurrentQueue, ConcurrentStack and ConcurrentBag are not suitable for a lot of purposes. For example those last three do not allow direct access to any element in the collection which makes them unfitting for many goals. In practical life it means that for general purpose thread-safety you can use as usually ConcurrentDictionary. 

But with little bit of imagination, you can use following usages of ConcurrentDictionary.

What you may want What you can use Comments, Warnings
List<T> ConcurrentDictionary<int, T> It will be slower then List, but it will be thread safe
HashSet<T> ConcurrentDictionary<T, T>  
SortedList<TKey, TValue> or SortedDictionary<TKey, TValue> ConcurrentDictionary<TKey, TValue> Sort before using

 

Now you may wonder what is purpose of ConcurrentQueue, ConcurrentStack, ConcurrentBag, BlockingCollection, IProducerConsumerCollection if they of such of limited usage? The answer is clear: they intended for producer/consumer scenarios. One thread puts something in collection or produced items in collections. Other threads taking items from collections or consuming them.

Few more words about Partitioners collections. They are needed for cases if you need to modify behavior of Parallel.ForEach.