控制器进行并行调用时如何等待结果 [英] How to wait for the result while controller is making parallel call

查看:108
本文介绍了控制器进行并行调用时如何等待结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从数据库(GetAccountDetailAsync)中查找一组帐户的帐户详细信息,并希望并行运行以使其更快.

I am trying to find account details from DB (GetAccountDetailAsync) for an array of accounts and would like to run in parallel to make it faster.

[HttpPost]
public async Task<IHttpActionResult> GetAccountsAsync(IEnumerable<int> accountIds)
{

    var resultAccounts = new List<AccountDetail>();

    var task = Task.Run(() =>
    {
        Parallel.ForEach(accountIds, new ParallelOptions
        {
            MaxDegreeOfParallelism = 5 
        }, async accountId =>
        {
            var response = await GetAccountDetailAsync(accountId).ConfigureAwait(false);
            resultAccounts.AddRange(response);

        });
    });

    task.Wait();

    return Ok(resultAccounts);

}

但是虽然得到了任务,但我没有得到结果,请稍等. 不确定为什么执行task.Wait没有被阻止.

But instead of getting the result I am getting though I've got task.Wait. Not sure why task.Wait is not being blocked.

异步模块或处理程序在异步操作仍处于挂起状态时完成."

推荐答案

Parallel.ForEach不适用于async动作,但是您可以启动所有任务,然后使用Task.WhenAll等待它们全部完成:

Parallel.ForEach doesn't work with async actions, but you could start all tasks and then wait for them all to complete using Task.WhenAll:

[HttpPost]
public async Task<IHttpActionResult> GetAccountsAsync(IEnumerable<int> accountIds)
{
    Task<List<AccountDetail>>[] tasks = accountIds.Select(accountId => GetAccountDetailAsync(accountId)).ToArray();
    List<AccountDetail>[] results = await Task.WhenAll(tasks);
    return Ok(results.SelectMany(x => x).ToList());
}

这篇关于控制器进行并行调用时如何等待结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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