In this blog, you will learn about C# ConcurrentBag class and how to use ConcurrentBag in C# code.ConcurrentBag is one of the thread-safe collection classes introduced in
.NET 4.0. ConcurrentBag allows you to store objects in unordered way.
How to initialize Concurrent Bag
ConcurrentBag<int> bag = new ConcurrentBag<int>();It will create a empty list of int type.
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.
List<int> lst = new List<int>();
lst.Add(7);You may add more items to the collection.
CountConcurrent bag provides the Count property that returns the number of items stored in the collection. The following code snippet reads the number of items
int cnt = bag.Count;
IsEmptyThe IsEmpty property returns true if the bag is empty. Else it returns false.
bool isEmpty = basg.IsEmpty;Retrieval of Data from the Concurrent Bag provides two ways to retrieve the data.
TryTakeSyntax - 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
bool result = bag.TryTake(out item);
TryPeekSyntax - 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
bool result = bag.TryPeek(out item);
ArrayIf you have returned the concurrent bag data in an array, then you have to use the ToArray method.
var result = bag.ToArray();
ClearThe Clear() method removes all items from the bag.
bag.Clear();Once called, the bag will be empty.
CopyToThe 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
int array = new int;