Chapter 1.8 C# – Using Concurrent Collections

When working in multithreaded environment you need to ensure that you are not manipulating the same data twice.

 

When using multithreading you must use the thread safe accessors to be ensured that data can be accessed safely.

 

The safe collections are

 

BlockingCollection<T>

 

This collection is thread-safe for adding and removing data.

Removing an item from the collection can be blocked until data becomes available. Adding data is fast but you can set upper limit. If the limit is reached adding an item blocks the calling thread until there is room

BlockingCollection is in reality a wrapper around other collection types. If you don’t give any specific instructions, it uses the ConcurrentQueue

 

A regular collection blows  up when being used in a multithreaded scenario because items might be removed while another thread is using it.

 

 

ConcurrrentBag<T>

 

ConcurrencyBag is a bag of items. I enables duplicated and has no order

 

Enables duplicates – key methods are Add,TryTake, tryPeek

 

ConcurrentQueue<T> /ConcurrentStack<T>

 

 

A stack is a last in, first out collection. Queue is a first in, first out (FIFO) collection.

 

ConcurrentStack has two important methods: Push and TryPop. Push is used to add an ityem to the stack; TryPop tries to get an item off the stack. You can never be sure whether there are items on the stack because multiple threads might be accessing your collection at the same time.

 

You can also try to remove items using PushRange and TryPopRange.

 

ConcurrentDictionary<TKey, T>

 

ConcurrentDictionary stores key value pairs in a thread safe manner.

It has methods to manipulate the data built in. It will be an atomic.

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *