控制器并行调用时如何等待结果

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


[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 没有被阻止。


“异步模块或处理程序已完成,而异步操作仍处于挂起状态。”


白板的微信
浏览 65回答 2
2回答

ibeautiful

Parallel.ForEach不适用于操作async,但您可以使用以下命令启动所有任务,然后等待它们全部完成Task.WhenAll:[HttpPost]public async Task<IHttpActionResult> GetAccountsAsync(IEnumerable<int> accountIds){&nbsp; &nbsp; Task<List<AccountDetail>>[] tasks = accountIds.Select(accountId => GetAccountDetailAsync(accountId)).ToArray();&nbsp; &nbsp; List<AccountDetail>[] results = await Task.WhenAll(tasks);&nbsp; &nbsp; return Ok(results.SelectMany(x => x).ToList());}

青春有我

GetAccountDetail假设您拥有或可以轻松获得没有异步部分的方法,这将是最简单的方法:[HttpPost]public async Task<IHttpActionResult> GetAccountsAsync(IEnumerable<int> accountIds){&nbsp; &nbsp;var resultList = accountIds.AsParallel()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .WithDegreeOfParallelism(5)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Select(GetAccountDetail)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .ToList();&nbsp; &nbsp;return Ok(resultList);}
打开App,查看更多内容
随时随地看视频慕课网APP