Ravi Vishwakarma is a dedicated Software Developer with a passion for crafting efficient and innovative solutions. With a keen eye for detail and years of experience, he excels in developing robust software systems that meet client needs. His expertise spans across multiple programming languages and technologies, making him a valuable asset in any software development project.
Ravi Vishwakarma
06-Mar-2025Thread-Safe Collection in C#
A thread-safe collection is a data structure designed to handle multiple threads accessing and modifying it concurrently without causing race conditions, data corruption, or requiring manual locking.
In multithreaded environments, standard collections like
List<T>
,Dictionary<K,V>
, andQueue<T>
are not thread-safe, meaning that simultaneous read/write operations from multiple threads can lead to undefined behavior.To solve this, .NET provides thread-safe collections under the
System.Collections.Concurrent
namespace.Why Use Thread-Safe Collections?
lock
keyword orMonitor
).Task.Run
,Parallel.ForEach
, etc.).Common Thread-Safe Collections in .NET
1.
ConcurrentDictionary<K, V>
A thread-safe version of
Dictionary<K, V>
, optimized for concurrent reads and writes.Example Usage
Why use it?
TryAdd()
,TryGetValue()
, andGetOrAdd()
.2.
ConcurrentQueue<T>
A thread-safe FIFO (First-In-First-Out) queue, useful for producer-consumer scenarios.
Why use it?
3.
ConcurrentStack<T>
A thread-safe LIFO (Last-In-First-Out) stack.
Why use it?
4.
ConcurrentBag<T>
A unordered collection optimized for fast insertions and removals across multiple threads.
Why use it?
5.
BlockingCollection<T>
A producer-consumer collection that allows blocking and bounded capacity.
Why use it?
Comparison of Thread-Safe Collections
ConcurrentDictionary<K,V>
ConcurrentQueue<T>
ConcurrentStack<T>
ConcurrentBag<T>
BlockingCollection<T>
Key Takeaways
lock
,Monitor
,Mutex
) where possible by using thread-safe collections.BlockingCollection<T>
if you need blocking behavior (e.g., waiting for elements to be available).ConcurrentDictionary<K, V>
is ideal for fast key-value lookups.