插入唯一键时是否需要 C# 中的 ConcurrentDictionary?

Do I need a ConcurrentDictionary in C# when I'm inserting unique keys?

我有一个场景,所有线程只会将唯一键插入字典。换句话说,没有两个线程会插入同一个键。我也没有任何更新或读取操作。这只是插入。在这种情况下我需要 ConcurrentDictionary 吗?

不,使用 Dictionary 不安全,因为 implemented as a hash table. Therefore when you add a new, unique key, the add method may start rehashing the whole dictionary. If another thread concurrently tries to add another key while the rehashing is taking place, you can end up with an inconsistent data structure. So you have to use a ConcurrentDictionary in your case. See also Microsoft's advice When to use a thread-safe collection