gpt4 book ai didi

c# - ConcurrentDictionary 陷阱 - 来自 GetOrAdd 和 AddOrUpdate 的委托(delegate)工厂是否同步?

转载 作者:IT王子 更新时间:2023-10-29 04:06:06 26 4
gpt4 key购买 nike

ConcurrentDictionary 的文档没有明确说明,所以我想我们不能期望委托(delegate) valueFactory updateValueFactory 同步执行(分别来自 GetOrAdd() 和 AddOrUpdate() 操作)。

因此,我认为我们无法在不手动实现我们自己的并发控制的情况下实现对其中需要并发控制的资源的使用,也许只是对委托(delegate)使用 [MethodImpl(MethodImplOptions.Synchronized)]

我说的对吗?或者 ConcurrentDictionary 是线程安全的,我们可以预期对这些委托(delegate)的调用会自动同步(也是线程安全的)?

最佳答案

是的,您是对的,ConcurrentDictionary 不同步用户委托(delegate)。如果您需要那些同步的,那是您的责任。

MSDN 本身说:

Also, although all methods of ConcurrentDictionary are thread-safe, not all methods are atomic, specifically GetOrAdd and AddOrUpdate. The user delegate that is passed to these methods is invoked outside of the dictionary's internal lock. (This is done to prevent unknown code from blocking all threads.)

See "How to: Add and Remove Items from a ConcurrentDictionary

这是因为 ConcurrentDictionary 不知道您提供的委托(delegate)将做什么或它的性能,所以如果它试图锁定它们,它可能会对性能产生负面影响并破坏 ConcurrentDictionary 的值(value).

因此,如果有必要,用户有责任同步他们的委托(delegate)。上面的 MSDN 链接实际上有一个很好的例子,说明它所做和不做的保证。

关于c# - ConcurrentDictionary 陷阱 - 来自 GetOrAdd 和 AddOrUpdate 的委托(delegate)工厂是否同步?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10486579/

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