Updated on
Concurrent Collections in C# are a set of collections designed for synchronized multi-thread access. We can find them under the System.Collections.Concurrent namespace, and they cover dictionaries, queues, stacks and bags.
There is no concurrent list or concurrent set, though. For those, a ConcurrentDictionary<T, byte>, a ConcurrentQueue<T> or a plain List<T> behind a lock does the job, depending on how we use the collection.
Let’s dig in.
What Are Concurrent Collections?
Concurrent collections are thread-safe collection classes from the System.Collections.Concurrent namespace. Several threads can add, remove and read items at the same time, and we don’t have to write a single lock to keep the collection consistent.
The namespace has five collection types. ConcurrentDictionary<TKey,TValue> stores key-value pairs, ConcurrentQueue<T> hands items back first in, first out, ConcurrentStack<T> hands them back last in, first out, and ConcurrentBag<T> keeps them in no particular order. BlockingCollection<T> wraps a queue, stack or bag and makes consumers wait until an item arrives.
Their methods look a bit different from the ones we know. Instead of Dequeue() or Pop(), we call TryDequeue() or TryPop(), which return false when the collection is empty, for example because another thread got there first.
We reach for them when more than one thread writes to the same collection. If threads only read a collection that nobody changes, the regular System.Collections.Generic types are fine.
The Problem of Generic Collections in Multi-Threading
All generic collections in .NET (such as Stack, Queue, List, Dictionary, and more) are not thread-safe. These collections address different data structure problems very well. Several threads can read one of them at the same time, as long as nobody changes it. But as soon as one thread writes while others read or write, we start to get inconsistent results. To better understand the thread safety problem of generic collections, we will use Dictionary<TKey,TValue> Â as an example.
Thread Safety Problem Example
Let’s create RoleManagerDictionary class that contains a member of type Dictionary<TKey,TValue>:
public class RoleManagerDictionary
{
private readonly Dictionary<string, User> _record;
public RoleManagerDictionary()
{
_record = new();
}
public async Task<bool> TryAssign(string role, int userId)
{
var user = await UserProvider.GetUser(userId);
return _record.TryAdd(role, user);
}
public IDictionary<string, User> GetAll()
{
return _record;
}
public void PrintAll()
{
Console.WriteLine($"No. of Records: {_record.Count}");
foreach (var (role, user) in _record)
{
Console.WriteLine($"Role: {role}, User: {user}");
}
}
}
The RoleManagerDictionary class contains one private member of type Dictionary<TKey,TValue> and a few methods. The TryAssign method is our area of interest.
Let’s inspect the program flow.
First, the method receives two arguments role and userId. In the next line, we use userId to get user information (from the UserProvider helper class in our sample, which returns a User record after a one-second delay). Once user information is retrieved, we try to add the provided role and user information to the dictionary and return true. However, if the role already exists in the _record it simply skips the add operation and returns false. The GetAll method returns the value of the private member, namely _record. Finally, the PrintAll method prints the values of _record to the console.
Let’s consume RoleManagerDictionary:
static async Task RunRoleManagerDictionaryExampleSync()
{
var roleManager = new RoleManagerDictionary();
await roleManager.TryAssign("Admin", 1);
await roleManager.TryAssign("Admin", 2);
await roleManager.TryAssign("Admin", 3);
roleManager.PrintAll();
}
All the tasks inside RunRoleManagerDictionaryExampleSync are running one after another, and there is no parallel operation taking place. Because our code doesn’t involve any concurrent access to _record the TryAssign method behaves as we expect it and when we invoke PrintAll we get one admin user.
Now let’s consume RoleManagerDictionary in parallel, which is where it breaks:
static async Task RunRoleManagerDictionaryExampleConcurrent()
{
var roleManager = new RoleManagerDictionary();
var task1 = roleManager.TryAssign("Admin", 1);
var task2 = roleManager.TryAssign("Admin", 2);
var task3 = roleManager.TryAssign("Admin", 3);
await Task.WhenAll(task1, task2, task3);
roleManager.PrintAll();
}
Inside RunRoleManagerDictionaryExampleConcurrent we create three tasks, and all of them have the same role. However, now because we are accessing the generic collection _record concurrently we start to get unpredictable outputs.
Let’s look at some of the outputs:
We ran the sample on .NET 11 with dotnet run -- --race, which runs only this method, and our runs either printed a single record, like the first and third runs in the screenshot, or threw the same InvalidOperationException as the fourth.
The outputs are far from our expectations and demonstrate the shortcomings of collections. Depending on the number of times we run the program, we will get different results: sometimes we get an exception, sometimes we get entries with the same dictionary key, and sometimes we get empty entries. All of this inconsistency is because Dictionary<TKey,TValue>Â are not thread-safe. This is the right place to use the concurrent variant of Dictionary<TKey,TValue>, which is ConcurrentDictionary<TKey,TValue>.
Solving The Example Thread Safety Problem
Dictionary<TKey,TValue> in .NET have a concurrent variant called ConcurrentDictionary<TKey,TValue>. It solves the same problem as Dictionary<TKey,TValue>. The main difference is thread safety. ConcurrentDictionary<TKey,TValue> is thread-safe, so concurrent access doesn’t corrupt it. For the full treatment, including which of the compound methods to reach for and which members take every lock, see ConcurrentDictionary in C#.
Let’s create RoleManagerConcurrentDictionary class that is similar to RoleManagerDictionary from our previous example. But this time, we will change the type of _record from Dictionary<TKey,TValue> to ConcurrentDictionary<TKey,TValue>:
using System.Collections.Concurrent;
public class RoleManagerConcurrentDictionary
{
private readonly ConcurrentDictionary<string, User> _record;
...
}
By changing the type of _record from Dictionary<TKey,TValue> to ConcurrentDictionary<TKey,TValue> we have extended our code to be thread-safe. Now we will consume RoleManagerConcurrentDictionary concurrently:
static async Task RunRoleManagerConcurrentDictionaryExampleConcurrent()
{
var concurrentRoleManager = new RoleManagerConcurrentDictionary();
var task1 = concurrentRoleManager.TryAssign("Admin", 1);
var task2 = concurrentRoleManager.TryAssign("Admin", 2);
var task3 = concurrentRoleManager.TryAssign("Admin", 3);
await Task.WhenAll(task1, task2, task3);
concurrentRoleManager.PrintAll();
}
Now regardless of the number of times we invoke the RunRoleManagerConcurrentDictionaryExampleConcurrent method, we will have only one admin user:
Which user wins changes from run to run, because the task that reaches TryAdd() first keeps the role, but there is always exactly one record.
What Are The Available Concurrent Collections?
To solve the issue with collections and concurrent access, .NET provides concurrent variants of some of them: ConcurrentDictionary<TKey,TValue>, ConcurrentQueue<T>, ConcurrentStack<T> and ConcurrentBag<T>. On top of those, BlockingCollection<T> adds waiting and an optional size limit to a queue, stack or bag.
It is important to note that not all collection classes have concurrent variants. List<T> and HashSet<T> are the two we miss most often, and we come back to them right after the three types below.
Concurrent Queue
Similar to Queue<T> the ConcurrentQueue<T> helps us to implement the FIFO data structure. The main difference is, ConcurrentQueue<T> is thread-safe. And it works reliably in multi-thread code. You can read more about a queue and the FIFO data structure in our previous article, Queue in C#. For everything the concurrent version can do, including why there is no Dequeue(), see our ConcurrentQueue in C# guide. In this section, we will look at how we can add, remove and get the state of ConcurrentQueue<T>.
Let’s start by creating UserLineConcurrentQueue class:
using System.Collections.Concurrent;
public class UserLineConcurrentQueue
{
private readonly ConcurrentQueue<User> _users;
public UserLineConcurrentQueue()
{
_users = new();
}
}
We will use the UserLineConcurrentQueue class to add users to a line, and serve the users inline. Once users are served they will be removed from the queue.
To add users to a line:
...
public async Task AddUser(int userId)
{
var user = await UserProvider.GetUser(userId);
_users.Enqueue(user);
}
...
ConcurrentQueue<T> contains Enqueue method to add elements to the queue.
Next, let’s add a method to serve users:
...
public bool TryServeUser(out User? user)
{
var isRemoved = _users.TryDequeue(out user);
if (isRemoved)
{
Console.WriteLine($"SERVED: {user}");
}
return isRemoved;
}
...
The TryServeUser method first tries to get the first user in the queue, and then we serve the user. For simplicity, we are not doing anything other than logging the user’s information.
It is important to note that unlike Queue<T>, ConcurrentQueue<T> doesn’t contain Dequeue method. Instead, it contains TryDequeue to get the first entry in the queue. Similarly, ConcurrentQueue<T> has TryPeek method but not Peek. This helps us to consider the possibility that the state of ConcurrentQueue<T> could have been updated by another thread accessing the ConcurrentQueue<T> at the same time.
Let’s add one more method to our example class to see who is first in line:
...
public User? LookWhoIsFirst()
{
if (_users.TryPeek(out User? user))
{
return user;
}
return default;
}
...
The TryPeek method retrieves the first element in the queue without removing it from the queue.
Concurrent Stack
The ConcurrentStack<T> is a thread-safe variant of Stack<T>. It helps us implement a LIFO data structure in a multi-threaded environment easily. To learn more about LIFO data structure and stack, please refer to our previous article, Stack in C#. For the concurrent type on its own, with PushRange() and TryPopRange(), see ConcurrentStack in C#.
To understand the usage of ConcurrentStack<T> let’s use a printer as an example, and we will add colored paper to a printer. The printer will then use the paper on top:
using System.Collections.Concurrent;
public class PrinterColorPaperConcurrentStack
{
private readonly ConcurrentStack<string> _paperColor;
public PrinterColorPaperConcurrentStack()
{
_paperColor = new ConcurrentStack<string>();
}
public void Add(string color)
{
_paperColor.Push(color);
}
public bool TryUse(out string? color)
{
return _paperColor.TryPop(out color);
}
public bool TryGetTop(out string? color)
{
return _paperColor.TryPeek(out color);
}
}
First, we start by defining and initializing the ConcurrentStack<string> instance. The Add method helps us to push the paper color to the paper stack. When the printer uses paper on top, that means we should remove it from the concurrent stack, the TryUse method helps us achieve exactly that. Last but not least, the TryGetTop allows us to know the color of the paper on top without removing it from the stack.
In ConcurrentStack<string> there is neither Pop nor Peek methods, instead we have TryPop and TryPeek.
Concurrent Bag
Unlike stack and queue, ConcurrentBag<T> store entries without any form of order. Moreover, it is possible to store duplicate entries and null values in ConcurrentBag<T>. For a full walkthrough of the type, including what order items come back in, see ConcurrentBag in C#.
ConcurrentBag<T> is optimized for situations where the same thread will both produce and consume the data from the bag.
Let’s look at how we can use ConcurrentBag<T>:
using System.Collections.Concurrent;
public class StorageConcurrentBag
{
private readonly ConcurrentBag<string> _files;
public StorageConcurrentBag()
{
_files = new();
}
public void AddNew(string fileName)
{
_files.Add(fileName);
}
public bool TryRemove(out string? removedFileName)
{
return _files.TryTake(out removedFileName);
}
public bool TryGet(out string? fileName)
{
return _files.TryPeek(out fileName);
}
}
The StorageConcurrentBag is a simple class we are using to manage files. We don’t care about the order of the files therefore, we will use the _files private member of type ConcurrentBag<string> to store the files.
ConcurrentBag<T> contains an Add method to add new entries, we are leveraging this method to add new files inside AddNew method.
Next, inside TryRemove we are calling the TryTake method to remove a file. The TryTake method retrieves one item from the bag and removes it from the bag. It returns true if there is an item otherwise false.
Finally, inside TryGet we are calling the TryPeek method. The TryPeek method retrieves an item from the bag but doesn’t remove it. It returns true if there is an item otherwise false.
Is There a Concurrent List or Concurrent Set in C#?
No. .NET has no ConcurrentList<T> and no ConcurrentHashSet<T>. What we use instead depends on what we need the collection for.
For a set, we use a ConcurrentDictionary<T, byte> and ignore the values. TryAdd() adds an item only when it isn’t there yet and returns false for a duplicate, TryRemove() takes it out, and ContainsKey() checks whether it’s there.
For a list, it depends on how we read it. If we only append and then read everything at the end, a ConcurrentQueue<T> keeps the items in the order they were added. If order doesn’t matter, a ConcurrentBag<T> works too. If we need an index, Insert() or Sort(), we keep a plain List<T> and guard every read and every write with a lock.
None of these is a full List<T> replacement. An index is hard to use safely when another thread can shift the items under it at any moment, so for index-based code we stay with the lock.
Let’s see the set first. Four workers each try to add the same 1,000 ids, so most of the calls are duplicates:
public static int CountUniqueIds(int workers, int idsPerWorker)
{
var seenIds = new ConcurrentDictionary<int, byte>();
Parallel.For(0, workers, _ =>
{
for (var id = 0; id < idsPerWorker; id++)
{
seenIds.TryAdd(id, 0);
}
});
return seenIds.Count;
}
This method and the two below go in a static ListAndSetAlternatives class, with using System.Collections.Concurrent; at the top of its file.
The value 0 means nothing. We only care about the keys, and TryAdd() makes sure each id is stored once no matter which worker gets there first.
For an append-only list, we swap in a ConcurrentQueue<T>:
public static int AppendToQueue(int workers, int itemsPerWorker)
{
var entries = new ConcurrentQueue<int>();
Parallel.For(0, workers, worker =>
{
for (var i = 0; i < itemsPerWorker; i++)
{
entries.Enqueue(worker * itemsPerWorker + i);
}
});
return entries.Count;
}
When we need what only List<T> has, we keep the list and lock around it:
public static int AppendToLockedList(int workers, int itemsPerWorker)
{
var numbers = new List<int>();
var numbersLock = new Lock();
Parallel.For(0, workers, worker =>
{
for (var i = 0; i < itemsPerWorker; i++)
{
lock (numbersLock)
{
numbers.Add(worker * itemsPerWorker + i);
}
}
});
return numbers.Count;
}
Since .NET 9, System.Threading.Lock is the type to lock on, and the lock statement works with it directly. On older versions, a private readonly object does the same job.
We call all three from Program.cs with four workers and 1,000 items each:
Console.WriteLine($"Unique ids: {ListAndSetAlternatives.CountUniqueIds(workers: 4, idsPerWorker: 1000)}");
Console.WriteLine($"Queued entries: {ListAndSetAlternatives.AppendToQueue(workers: 4, itemsPerWorker: 1000)}");
Console.WriteLine($"Locked list entries: {ListAndSetAlternatives.AppendToLockedList(workers: 4, itemsPerWorker: 1000)}");
The counts come out the same on every run:
Unique ids: 1000 Queued entries: 4000 Locked list entries: 4000
If none of these fits, it’s worth asking whether the collection needs to change at all once it’s built. Our article on immutable collections in C# covers the types that never change, which any number of threads can read without a lock.
The table maps each collection we’d use in single-threaded code to its thread-safe choice:
| In single-threaded code | Thread-safe choice | Good to know |
|---|---|---|
Dictionary<TKey,TValue> | ConcurrentDictionary<TKey,TValue> | Use TryAdd(), TryRemove() and TryGetValue() |
Queue<T> | ConcurrentQueue<T> | First in, first out, TryDequeue() instead of Dequeue() |
Stack<T> | ConcurrentStack<T> | Last in, first out, TryPop() instead of Pop() |
HashSet<T> | ConcurrentDictionary<T, byte> | There is no concurrent set; the keys are the set |
List<T>, append and read at the end | ConcurrentQueue<T> | Keeps the order items were added in |
List<T>, order doesn't matter | ConcurrentBag<T> | Unordered, allows duplicates |
List<T>, with index access | List<T> with a lock | Every read and every write inside the lock |
| A queue that consumers wait on | BlockingCollection<T> or a Channel<T> | Consumers wait until an item arrives |
Benefits of Concurrent Collections
In the previous example, we saw the problem of using generic collections in a multi-threaded environment. We can resolve the issue by simply changing the type from Dictionary<TKey,TValue> to ConcurrentDictionary<TKey,TValue>. This is an oversimplified example, and real-life scenarios are likely to require more work. However, in both cases, concurrent collections make our life as a developer easier by providing us with thread-safe collections that don’t need us to write any additional code for thread synchronization and data safety across multiple threads.
Microsoft Learn’s page on thread-safe collections puts it the same way: “Multiple threads can safely and efficiently add or remove items from these collections, without requiring additional synchronization in user code.”
Concurrent Collection Caveats
Concurrent collections make it a breeze to use collections in a multi-threaded environment. However, when we are using concurrent collections, it is important to take into account a few things:
- In single-threaded code, concurrent collections still do their synchronization work, even though no other thread needs it. If only one thread ever touches the collection, a regular generic collection is the better fit.
- Our code should read the state of the whole collection, such as
Count,IsEmptyorToArray(), as rarely as possible. On some types these members have to synchronize with every thread using the collection, and the answer can be out of date by the time we act on it. - When there is a simultaneous update on the state of concurrent collections by multiple threads, concurrent collections don’t guarantee which change is going to take precedence.
- For
ConcurrentDictionary<TKey,TValue>andConcurrentBag<T>, Microsoft Learn doesn’t guarantee that calls through an interface the collection implements, LINQ extension methods included, are thread-safe. That’s why our sample reads theCountproperty instead of callingCount().
Conclusion
In this article, we have learned what concurrent collections are and why generic collections break when several threads write to them. We’ve looked at the types System.Collections.Concurrent gives us, and at what to use when we need a thread-safe list or set, which .NET doesn’t have. Finally, we’ve covered the benefits and the caveats of concurrent collections.
Tested with .NET 11 (SDK 11.0.100, runtime 11.0.0) and xUnit 2.9.3.


