C# Dictionary 并发添加或修改仅针对不同的键,是否需要ConcurrentDictionary?

C# Dictionary concurrent add or modify only for different keys, is ConcurrentDictionary necessary?

我有一个字典只支持addmodify操作,可以并发操作,但是always for different keys。键是 int,值是引用类型。修改也意味着更改值的某些属性。

我的问题是:

  1. 在这种情况下是否需要使用 ConcurrentDictionary?如果需要,它有什么帮助?
  2. 如果可以对同一个键进行并发修改,ConcurrentDictionary 是否有助于确保线程安全?我的理解是不对,对吗?

谢谢!

找出这一点的最佳方法是查看 MSDN 文档。

对于ConcurrentDictionary,页面是http://msdn.microsoft.com/en-us/library/dd287191.aspx

在线程安全部分,声明为"All public and protected members of ConcurrentDictionary<TKey, TValue> are thread-safe and may be used concurrently from multiple threads."

Do I need to use ConcurrentDictionary in this scenario? If needed, how does it help?

是的,如果多个线程同时添加或删除条目,标准词典将无法正常运行。 (尽管如果没有其他人修改它,多个线程同时读取它是安全的)。

If concurrent modification can happen on the same key, will ConcurrentDictionary help to ensure thread safety? My understanding is no, is that correct?

如果你问的是"Will the concurrent dictionary prevent multiple threads from accessing the values inside the dictionary at the same time?",那么不,不会。

如果要防止多个线程同时访问同一个值,则需要使用某种并发控制,例如锁定。