异步填充字典 [英] Populate dictionary asynchronously

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

问题描述

我有一个简单的 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屋!

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