ConcurrentDictionary GetOr添加异步 [英] ConcurrentDictionary GetOrAdd async

查看:152
本文介绍了ConcurrentDictionary GetOr添加异步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 GetOrAdd 之类的东西和 ConcurrentDictionary 作为Web服务的缓存。该词典有异步版本吗? GetOrAdd将使用 HttpClient 发出Web请求,因此,如果该词典的某个版本中GetOrAdd是异步的,那就太好了。

I want to use something like GetOrAdd with a ConcurrentDictionary as a cache to a webservice. Is there an async version of this dictionary? GetOrAdd will be making a web request using HttpClient, so it would be nice if there was a version of this dictionary where GetOrAdd was async.

为消除混乱,词典的内容将是对Web服务的调用的响应。

To clear up some confusion, the contents of the dictionary will be the response from a call to a webservice.

ConcurrentDictionary<string, Response> _cache = new ConcurrentDictionary<string, Response>();



var response = _cache.GetOrAdd("id", (x) => { _httpClient.GetAsync(x).GetAwaiter().GetResponse();} )


推荐答案

GetOrAdd 不会成为异步操作,因为访问字典的值不是一个长期运行的操作。

GetOrAdd won't become an asynchronous operation because accessing the value of a dictionary isn't a long running operation.

但是您可以做的只是存储任务在字典中,而不是具体的结果。任何需要结果的人都可以等待该任务。

What you can do however is simply store tasks in the dictionary, rather than the materialized result. Anyone needing the results can then await that task.

但是,您还需要确保操作仅启动一次,而不是多次启动。为了确保某些操作仅运行一次,而不是多次运行,还需要添加 Lazy

However, you also need to ensure that the operation is only ever started once, and not multiple times. To ensure that some operation runs only once, and not multiple times, you also need to add in Lazy:

ConcurrentDictionary<string, Lazy<Task<Response>>> _cache = new ConcurrentDictionary<string, Lazy<Task<Response>>>();

var response = await _cache.GetOrAdd("id", url => new Lazy<Task<Response>>(_httpClient.GetAsync(url))).Value;

这篇关于ConcurrentDictionary GetOr添加异步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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