如何使用异步调用的结果来对字典进行水化处理? [英] How to hydrate a Dictionary with the results of async calls?

查看:48
本文介绍了如何使用异步调用的结果来对字典进行水化处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有如下代码:

public async Task<string> DoSomethingReturnString(int n) { ... }
int[] numbers = new int[] { 1, 2 , 3};

假设我要创建一个字典,其中包含对每个与此相似的数字调用DoSomethingReturnString的结果:

Suppose that I want to create a dictionary that contains the result of calling DoSomethingReturnString for each number similar to this:

Dictionary<int, string> dictionary = numbers.ToDictionary(n => n,
    n => DoSomethingReturnString(n));

那是行不通的,因为DoSomethingReturnString返回Task<string>而不是string.明智的建议是,我尝试将lambda表达式指定为异步,但这似乎也无法解决问题.

That won't work because DoSomethingReturnString returns Task<string> rather than string. The intellisense suggested that I try specifying my lambda expression to be async, but this didn't seem to fix the problem either.

推荐答案

如果您坚持使用linq进行操作,Task.WhenAll是补充"字典的关键:

If you insist on doing it with linq, Task.WhenAll is the key to "hydrate" the dictionary:

int[] numbers = new int[] { 1, 2 , 3};

KeyValuePair<int, string>[] keyValArray = //using KeyValuePair<,> to avoid GC pressure
    await Task.WhenAll(numbers.Select(async p => 
        new KeyValuePair<int, string>(p, await DoSomethingReturnString(p))));

Dictionary<int, string> dict = keyValArray.ToDictionary(p => p.Key, p => p.Value);

这篇关于如何使用异步调用的结果来对字典进行水化处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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