我有一些用户。每个用户都有一个产品列表。每个用户都使用他们的产品存储在blob存储中,所以我想并行检索它们,我可以做得很好。
问题在于,当返回每组产品时,我不知道他们与哪个用户有关。
代码:
var tasks = users.Select(u => this.repository.GetProducts(u.UserName)).ToList();
var producstByUser = await Task.WhenAll(tasks);
foreach(List<Product> products in productsByUser)
{
//how do I know which user each set of products are for??
}
有没有办法可以将一些元数据附加到任务调用或其他什么?也许我会以完全错误的方式解决这个问题?
答案 0 :(得分:3)
是的,你做错了。异步等待的目的是保持简单的控制流,同时异步运行代码。
var tasks = users.Select(async user =>
{
var products = await this.repository.GetProducts(user.UserName);
return new { user, products };
});
var results = await Task.WhenAll(tasks);
var resultsAsDictionary = results(x => x.user, x => x.products);
答案 1 :(得分:2)
创建匿名类型/命名类型。
var items = users.Select(u => new
{
User = u,
ProductsTask = this.repository.GetProducts(u.UserName)
}).ToList();
await Task.WhenAll(items.Select(x => x.ProductsTask));
//Ignore the return value of `WhenAll` and just use the `items` collection
foreach (var item in items)
{
var user = item.User;
List<Product> products = item.ProductsTask.Result;
//Accessing Task.Result is fine here, we know task already completed.
}
答案 2 :(得分:1)
你可以:
var tasks = users.Select(u =>
this.repository
.GetProducts(u.UserName)
.ContinueWith(products=>Tuple.Create(u, products.Result.ToList())));
var producstByUser = await Task.WhenAll(tasks);
foreach(Tuple<User, List<Product>> products in productsByUser)
{
//products.Item1 is the user
//products.Item2 are the products for the user
}