gpt4 book ai didi

c# - 从 Dictionary 迁移到 ConcurrentDictionary,我应该注意哪些常见陷阱?

转载 作者:行者123 更新时间:2023-12-03 07:58:39 24 4
gpt4 key购买 nike

我正在考虑从 Dictionary 迁移到 ConcurrentDictionary 以实现多线程环境。

具体到我的用例,kvp 通常是 <string, List<T>>

  • 我需要注意什么?
  • 如何成功实现线程安全?
  • 如何管理在不同线程中读取键和值?
  • 如何管理不同线程中键和值的更新?
  • 如何管理在不同线程中添加/删除键和值?

最佳答案

What do I need to look out for?

取决于您想要实现的目标:)

How do I manage reading key and values in different threads?
How do I manage updating key and values in different threads?
How do I manage adding/removing key and values in different threads?

这些应该由字典本身以线程安全的方式处理。有几个警告:

  • 接受像 ConcurrentDictionary<TKey,TValue>.GetOrAdd(TKey, Func<TKey,TValue>) 这样的工厂的函数就工厂调用而言不是线程安全的(例如,如果多个线程尝试获取或添加项目,字典不保证工厂只会被调用一次)。引用文档:

    All these operations are atomic and are thread-safe with regards to all other operations on the ConcurrentDictionary<TKey,TValue> class. The only exceptions are the methods that accept a delegate, that is, AddOrUpdate and GetOrAdd. For modifications and write operations to the dictionary, ConcurrentDictionary<TKey,TValue> uses fine-grained locking to ensure thread safety. (Read operations on the dictionary are performed in a lock-free manner.) However, delegates for these methods are called outside the locks to avoid the problems that can arise from executing unknown code under a lock. Therefore, the code executed by these delegates is not subject to the atomicity of the operation.

  • 在您的特定情况下,值 - List<T>本身不是线程安全的,因此虽然字典操作将是线程安全的(上一点除外),但具有值本身的变异操作不会,请考虑使用类似 ConcurrentBag 的东西。或切换至IReadOnlyDictionary .

  • 就我个人而言,我会谨慎地通过显式实现的接口(interface)(如 IDictionary<TKey, TValue>)使用并发字典。和/或索引器(可能导致读取-更新-写入场景中的竞争条件)。

关于c# - 从 Dictionary 迁移到 ConcurrentDictionary,我应该注意哪些常见陷阱?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75131392/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com