C# Interview Question #111

What are concurrent collections in .NET?

Concurrency, Performance & Design Senior Advanced

Quick Interview Answer

Concurrent collections are thread-safe collection types designed for access by multiple threads.

Detailed Explanation

Concurrent collections are thread-safe collection types designed for access by multiple threads.

Examples include ConcurrentDictionary<TKey,TValue>, ConcurrentQueue<T>, ConcurrentStack<T>, and ConcurrentBag<T>. They provide atomic operations and internal synchronization strategies that are usually safer and more scalable than manually locking a normal collection for every operation.

They do not automatically make the objects stored inside them thread-safe; mutable values may still require synchronization.

Code Example

var cache = new ConcurrentDictionary<int, string>();

cache.TryAdd(1, "Product A");

string value = cache.GetOrAdd(
    2,
    _ => "Product B");