ConcurrentDictionary陷阱 - 从GetOrAdd和AddOrUpdate代表工厂同步? [英] ConcurrentDictionary Pitfall - Are delegates factories from GetOrAdd and AddOrUpdate synchronized?

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

问题描述

的文档 ConcurrentDictionary 不明确的,所以我想我们不能指望代表的 valueFactory updateValueFactory 的有自己的执行sinchronized(从GetOrAdd()和AddOrUpdate分别为()操作的)

The documentation of ConcurrentDictionary doesn't explicit it, so I guess we cannot expect that delegates valueFactory and updateValueFactory have their execution sinchronized (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 是线程安全的,我们可以预期,调用这些代表会自动sinchronized(线程安全的太)?

Am I right ? Or the fact that ConcurrentDictionary is thread-safe we can expect that calls to these delegates are automatically sinchronized (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。传递给这些方法的用户的委托是   该词典的内部锁外调用。 (这样做是为了   prevent未知code阻塞所有线程。)

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天全站免登陆