ConcurrentDictionary 陷阱 - GetOrAdd 和 AddOrUpdate 的委托工厂是否同步? [英] ConcurrentDictionary Pitfall - Are delegates factories from GetOrAdd and AddOrUpdate synchronized?

查看:41
本文介绍了ConcurrentDictionary 陷阱 - GetOrAdd 和 AddOrUpdate 的委托工厂是否同步?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ConcurrentDictionary 的文档没有明确说明,所以我想我们不能指望委托 valueFactoryupdateValueFactory 使它们的执行同步(分别来自 GetOrAdd() 和 AddOrUpdate() 操作).

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 和添加或更新.传递给这些方法的用户委托是在字典的内部锁之外调用.(这样做是为了防止未知代码阻塞所有线程.)

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 链接实际上有一个很好的例子,说明了它所做和不做的保证.

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 陷阱 - GetOrAdd 和 AddOrUpdate 的委托工厂是否同步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆