ConcurrentBag<T>
is one of the simplest concurrent collections. It is intended to store any general-purpose data. The main feature of this collection is how it stores the data; the Add
method appends an item to a doubly-linked list that is stored in the current thread's local storage. This makes the appending operation very efficient, since there is no contention. Getting an item from the collection with the TryTake
or TryPeek
methods is also quite efficient. First, we look for the item in the local list, but if it is empty, we look for items in other threads' local lists.
This approach is called work stealing and works well when each thread contains more or less the same number of data and uses the same number of append and take operations.
Let's review an example of using the ConcurrentBag<T>
data structure:
var bag = new ConcurrentBag<string>(); var task1 = Run(() => { AddAndPrint(bag, "[T1]: Item 1"); AddAndPrint(bag, "[T1]: Item 2...