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
- 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(5);
- lst.Add(6);
- lst.Add(7);
You may add more items to the collection.
- lst.Add(10);
- 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.
IsEmpty
The 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.
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
- int item;
- 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
- int item;
- 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.
- var result = bag.ToArray();
Clear
The Clear() method removes all items from the bag.
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
- int[] array = new int[10];
- bag.CopyTo(array, 2);