异步填充字典 [英] Populate dictionary asynchronously
本文介绍了异步填充字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个简单的 foreach
循环(如下所示),该循环遍历一个集合并进行异步API调用以根据当前的迭代器值获取数据.
I have a simple foreach
loop (as below) that iterates over a collection and makes an async API call to fetch data based on the current iterator value.
foreach (var group in groups)
{
var usersInGroup = await this.tableauService.GetUsersInTableauGroup(group.Id);
// do work with `usersInGroup`
}
我不想为每个迭代创建一个API调用,而是要为每个API调用创建一个异步任务,并同时执行所有任务,其结果将填充由 group.Id
键控的字典..这可能吗?
Instead of making an API call each iteration, I want to create an async task for each API call and execute them all at the same time, with the results populating a dictionary keyed by group.Id
. Is this possible?
在我的脑海中,代码看起来像这样:
In my head, the code would look something like:
IList<Task<string[]>> tasks = new List<Task<string[]>>();
IDictionary<string, string[]> dictionary = new Dictionary<string, string[]>();
foreach (var group in groups)
{
tasks.Add(this.tableauService.GetUsersInTableauGroup(group.Id));
// Somehow define callback of each task to hydrate dictionary
}
await Task.WhenAll(tasks);
推荐答案
Task.WhenAll()返回任务的所有值,因此您可以执行以下操作:
Task.WhenAll() returns all the values of the tasks, so you can do something like this:
var tasks = groups
.Select(async g => new
{
g.Id,
Values = await this.tableauService.GetUsersInTableauGroup(g.Id)
});
var results = await Task.WhenAll(tasks);
var dictionary = results
.ToDictionary(r => r.Id, r => r.Values);
这篇关于异步填充字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文