C# Dictionary<T,K> 线程安全,单个 writer 多个 reader

C# Dictionary<T,K> thread-safety with single writer multiple reader

A Dictionary can support multiple readers concurrently, as long as the collection is not modified. Even so, enumerating through a collection is intrinsically not a thread-safe procedure. In the rare case where an enumeration contends with write accesses, the collection must be locked during the entire enumeration. To allow the collection to be accessed by multiple threads for reading and writing, you must implement your own synchronization.

MSDN 是这么说的。

如果没有必要,我不想使用 ConcurrentDictionary

我假设,如果只有一个线程在 Dictionary<T,K> 上执行写入操作,其他线程同时执行简单的读取操作(如 TryGetValue 而不是枚举)是安全的,而无需获得锁,我说得对吗?

I assume, if there is only one thread performing writer operations on Dictionary, it is safe for other threads to perform simple reading operations(like TryGetValue not enumeration) at the same time without acquiring a lock

没有。你的假设是错误的。只有当没有作者在修改字典时才是安全的,而不是当你只有一个作者时。

ReaderWriterLockSlim is exactly designed to be used in this scenario. That said I'd just use ConcurrentDictionary而不是重新发明轮子

旧的System.Collections.Hashtable对于多读单写的场景是安全的,即任意数量的线程都可以读取Hashtable,但是最多一个线程可以同时修改它。 (写入者线程可以在读者读取 Hashtable 时安全地修改它)。

通用 Dictionary<T,K> 对于此类情况不安全 - 请改用 ConcurrentDictionary<T,K>

请注意 System.Collections.HashtableConcurrentDictionary<T,K> 使用完全不同的实现并提供不同的 API。 ConcurrentDictionary<T,K>非常适合惰性初始化、缓存读取等场景。 System.Collections.Hashtable 性能更高,因为它是一种无锁数据结构,而 ConcurrentDictionary<T,K> 使用线程同步编组到 Windows API。