ConcurrentBag
Learn the unordered thread-safe bag with ConcurrentBag.
ConcurrentBag
ConcurrentBag<T> is an unordered thread-safe bag. There is no FIFO or LIFO guarantee; each thread has a local list and pops from its own first.
It is the fastest choice when the same thread both adds and removes. When order does not matter and you do parallel produce-consume work, ConcurrentBag is a good pick.
When to use ConcurrentBag?
Use ConcurrentBag when order does not matter and the same thread usually adds and removes. When order matters, pick ConcurrentQueue or ConcurrentStack.
Because it is unordered, testing with ToArray() followed by OrderBy makes the output deterministic. Otherwise the order of items on screen is variable.
Exercise Add to the bag and print sorted
The bag below is empty. Use Add to add three items: "log", "read", "write". First print bag.Count. Then print each item sorted alphabetically with bag.ToArray().OrderBy(x => x).
Show example solution
bag.Add("log"); bag.Add("read"); bag.Add("write"); Console.WriteLine(bag.Count); Then foreach (var item in bag.ToArray().OrderBy(x => x)) Console.WriteLine(item);
Example solution:
using System;
using System.Collections.Concurrent;
using System.Linq;
class Program
{
static void Main()
{
var bag = new ConcurrentBag<string>();
bag.Add("log");
bag.Add("read");
bag.Add("write");
Console.WriteLine(bag.Count);
foreach (var item in bag.ToArray().OrderBy(x => x))
{
Console.WriteLine(item);
}
}
}
Test yourself
-
What ordering guarantee does ConcurrentBag make?
- FIFO order
- LIFO order
- Unordered, thread-safe
- Sorted
Show answer
Unordered, thread-safe — Correct. ConcurrentBag is unordered; it makes no order promise.
-
Match each bag method
- Add
- Add an item to the bag
- TryTake
- Remove an item from the bag
- Count
- Return the number of items
-
Complete the Add call
bag.____;Show answer
bag.Add("task");