是否确保ConcurrentDictionary.GetOrAdd()每个键仅调用一次valueFactoryMethod? [英] Is ConcurrentDictionary.GetOrAdd() guaranteed to invoke valueFactoryMethod only once per key?

查看:89
本文介绍了是否确保ConcurrentDictionary.GetOrAdd()每个键仅调用一次valueFactoryMethod?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题::我需要实现对象缓存.缓存必须是线程安全的,并且需要按需填充值(延迟加载).通过Key(慢速操作)通过Web服务检索值.因此,我决定使用ConcurrentDictionary及其 GetOrAdd() a>具有值工厂方法的方法,假定该操作是原子操作且已同步.不幸的是,我在MSDN文章中发现以下语句:如何:从ConcurrentDictionary中添加和删除项:

Problem: I need to implement object cache. The cache need to be thread-safe and need to populate values on demand(lazy loading). The values are retrieved via web service by Key(slow operation). So I've decided to use ConcurrentDictionary and its GetOrAdd() method that has a value factory method supposing that the operation is atomic and synchronized. Unfortunately I found the following statement in the MSDN article: How to: Add and Remove Items from a ConcurrentDictionary:

尽管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.

不幸的是,但是仍然不能完全回答我的答案.

Well that's unfortunate but still doesn't answer my answer completely.

问题::每个键值工厂仅被调用一次吗?在我的特定情况下:正在寻找同一个键的多个线程是否可能会为Web服务生成多个具有相同值的请求?

Question: Is value factory invoked only once per key? In my specific case: Is it possible that multiple threads that are looking for the same key spawning multiple request to the web service for the same value?

推荐答案

每个键只调用一次值工厂吗?

Is value factory invoked only once per key?

不,不是. 文档说:

如果您同时在不同的线程上调用GetOrAdd valueFactory可以被多次调用,但是它的键/值对可能不会添加到 每次通话的字典.

If you call GetOrAdd simultaneously on different threads, valueFactory may be invoked multiple times, but its key/value pair might not be added to the dictionary for every call.

这篇关于是否确保ConcurrentDictionary.GetOrAdd()每个键仅调用一次valueFactoryMethod?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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