ConcurrentDictionary Pitfall - 来自GetOrAdd和AddOrUpdate的委托工厂是否同步? [英] ConcurrentDictionary Pitfall - Are delegates factories from GetOrAdd and AddOrUpdate synchronized?
问题描述
ConcurrentDictionary
的文档没有显式状态,所以我想我们不能期望委托 valueFactory
和分别从GetOrAdd()和AddOrUpdate()操作同步执行 和 updateValueFactory
。
The documentation of ConcurrentDictionary
doesn't explicit state, so I guess we cannot expect that delegates valueFactory
and updateValueFactory
have their execution synchronized (from GetOrAdd() and AddOrUpdate() operations respectively).
所以,我认为我们不能实现在其中需要并发控制的资源,而不需要手动实现我们自己的并发控制,也许只是使用 [ MethodImpl(MethodImplOptions.Synchronized)]
。
So, I think we cannot implement use of resources inside them which need concurrent control without manually implementing our own concurrent control, maybe just using [MethodImpl(MethodImplOptions.Synchronized)]
over the delegates.
我是对吗?或者事实, ConcurrentDictionary
是线程安全的,我们可以期望对这些委托的调用自动同步(线程安全太)?
Am I right? Or the fact that ConcurrentDictionary
is thread-safe we can expect that calls to these delegates are automatically synchronized (thread-safe too)?
推荐答案
是的,你是对的,用户代理不是由 ConcurrentDictionary
同步的。如果你需要那些同步的,这是你的责任。
Yes, you are right, the user delegates are not synchronized by ConcurrentDictionary
. If you need those synchronized it is your responsibility.
MSDN本身说:
此外,虽然ConcurrentDictionary的所有方法
线程安全,不是所有的方法都是原子的,特别是GetOrAdd和
AddOrUpdate。传递给这些方法的用户委托是在字典内部锁之外调用的
。 (这是为了
防止未知代码阻塞所有线程。)
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.)
请参阅如何从ConcurrentDictionary中添加和删除项目
这是因为 ConcurrentDictionary
不知道你提供的委托将做什么或它的性能,所以如果它试图锁定他们,它可能真的影响性能负面,破坏ConcurrentDictionary。
This is because the ConcurrentDictionary
has no idea what the delegate you provide will do or its performance, so if it attempted lock around them, it could really impact performance negatively and ruin the value of the ConcurrentDictionary.
因此,如果有必要的话,用户有责任同步他们的委托。上面的MSDN链接实际上有一个很好的例子, make。
Thus, it is the user's responsibility to synchronize their delegate if that is necessary. The MSDN link above actually has a good example of the guarantees it does and does not make.
这篇关于ConcurrentDictionary Pitfall - 来自GetOrAdd和AddOrUpdate的委托工厂是否同步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!