ConcurrentBag In C#

In this blog, you will learn about C# ConcurrentBag class and how to use ConcurrentBag in C# code.

ConcurrentBag

 
ConcurrentBag is a collection class and is declared in System.Collections.Concurrent namespace. It allows generic data to be stored in unordered from. Bags support duplicates. It is a thread-safe class and allows multiple threads to use it. 
 

How to initialize Concurrent Bag

  1. ConcurrentBag<int> bag = new ConcurrentBag<int>();  
It will create a empty list of int type.
  1. ConcurrentBag<int> bag = new ConcurrentBag<int>(lst);  
The Add() method is used to add items to the bag. The items can be any object. In this case, int. The following code snippet adds three items to the collection.
  1. List<int> lst = new List<int>();  
  2. lst.Add(5);  
  3. lst.Add(6);  
  4. lst.Add(7);  
You may add more items to the collection.
  1. lst.Add(10);  
  2. lst.Add(14);  

Count

 
Concurrent bag provides the Count property that returns the number of items stored in the collection. The following code snippet reads the number of items.
  1. int cnt = bag.Count;
 

IsEmpty

 
The IsEmpty property returns true if the bag is empty. Else it returns false. 
  1. bool isEmpty = basg.IsEmpty;  
 
Retrieval of Data from the Concurrent Bag provides two ways to retrieve the data.
  1. TryTake
  2. TryPeek

TryTake

 
Syntax - bool TryTake (out T result)
 
It will return the first element of the concurrent bag. The return value is returned as an out parameter. The method also removes the item from the bag.
 
Example
  1. int item;  
  2. bool result = bag.TryTake(out item);  

TryPeek

 
Syntax - bool TryPeek(out T result)
 
It will return the first element of the concurrent bag found in the collection as an out parameter. Unlike TryTake, this method does not remove the item.
 
Example
  1. int item;  
  2. bool result = bag.TryPeek(out item);  

Array

 
If you have returned the concurrent bag data in an array, then you have to use the ToArray method.
  1. var result = bag.ToArray();  

Clear

 
The Clear() method removes all items from the bag.
  1. bag.Clear();  
Once called, the bag will be empty.
 

CopyTo

 
The CopyTo method copies the ConcurrentBag<T> elements to an existing one-dimensional Array, starting at the specified array index. 
 
Syntax - CopyTo(T[] array, int index)
 
Example
  1. int[] array = new int[10];  
  2. bag.CopyTo(array, 2);