BlockingCollection C#

 BlockingCollection is a wrapper around thread safe collections  that implements   IProducerConsumerCollection<T>.

According to the Producer-Consumer pattern implemented by the BlockingCollection, the producer adds data to the collection and the consumer consumes/removes data from the collection on a different thread.

Blocking collection provides Blocking and Bounding features to the Concurrent Collections.

Bounding : It defines the maximum size of the collection after which no new items can be added to collection until the existing ones are removed.

Blocking :  When a producer thread reaches BlockingCollection maximum limit, it is blocked to add new objects and when collection class is empty, the consumer thread is blocked until the producer thread adds new item.

Instantiation of blocking collection:

There are two methods to add new items.

  1. Add
  2. TryAdd

Add Method

TryAdd

 In TryAdd method,timeout value can be set. If the add operation fails within the specified time, the TryAdd method returns false. The following code snippet shows how you can take advantage of the TryAdd method to add an item to an instance of BlockingCollection

Remove Items

BlockingCollection provides two methods to remove items from collection

  1. Take
  2. TryTake

Take Method

Take method removes an item from the collection. Take method is blocked when the collection is empty. It’ll unblock when any item is added by other thread.

TryTake Method

TryTake method also removes an item and returns item in the out parameter. This method also takes a timeout parameter. If the collection is empty then this method will wait for time specify in timeout parameter. If new item is not added within the timeout value, then it returns false.

Here is complete sample to use blocking collection with Task.