Concurrent Collections & Synchronization
Prerequisites: Multithreading with the Task Parallel Library
private readonly object _lock = new();
private int _count = 0;
public void Increment() {
lock (_lock) {
_count++;
}
}
lock is C#'s equivalent of Java's synchronized block. For
collections shared across threads, System.Collections.Concurrent
provides ready-made thread-safe types
(ConcurrentDictionary<TKey, TValue>,
ConcurrentQueue<T>) instead of manually locking around an
ordinary Dictionary.
Common mistakes
- Reading and modifying a plain
Dictionaryfrom multiple threads with nolockat all — this is a race condition, and can even corrupt the dictionary's internal structure, not just produce a wrong value.