Sobes.tech
Junior — Middle

What are thread-safe collections and how do they work in multithreaded programming?

sobes.tech AI

Answer from AI

Thread-safe collections in C# are data structures that can be safely used concurrently from multiple threads without risking data corruption or race conditions. They implement internal synchronization, for example, using locks, atomic operations, or lock-free algorithms.

An example of a thread-safe collection is the ConcurrentDictionary<TKey, TValue> class. It allows multiple threads to read and modify the dictionary simultaneously without external synchronization.

Example usage:

using System.Collections.Concurrent;

var dict = new ConcurrentDictionary<int, string>();
dict.TryAdd(1, "one");
dict[2] = "two";

// Operations can be performed safely in multiple threads:
string value;
if (dict.TryGetValue(1, out value))
{
    Console.WriteLine(value);
}

Thus, thread-safe collections simplify the development of multithreaded applications, eliminating the need to manually write synchronization code when working with shared data.