[英]Nested Async/Await Doesn't Appear To Be Scaling
我有以下(簡化)代碼:
public async Task GetData(DomainObject domainObject, int depth)
{
// This async operation is really quick, and there's usually like five.
IEnumerable<TierOne> tierOnes = await domainObject.GetTierOnesAsync();
var tierOneTasks = tierOnes.Select(async tierOne =>
{
// This async operation is really quick and there's usually like three.
IEnumerable<TierTwo> tierTwos = await tierOne.GetTierTwosAsync();
if (depth <= TierTwoDepth)
return;
var tierTwoTasks = tierTwos.Select(async tierTwo =>
{
// This async operation is usually fast, and there's usually >= 100.
IEnumerable<TierThree> tierThrees = await tierTwo.GetTierThreesAsync();
if (depth <= TierThreeDepth)
return;
var tierThreeTasks = tierThrees.Select(async tierThree =>
{
// This async operation is SLOW, and there's usually.. 50?
await tierThree.GetTierFoursAsync();
});
await Task.WhenAll(tierThreeTasks.ToArray());
});
await Task.WhenAll(tierTwoTasks.ToArray());
});
await Task.WhenAll(tierOneTasks.ToArray());
}
基於我所看到的,它似乎沒有很好地擴展。 所有Async
操作都是“真正的異步”操作,這意味着它們都是I / O.
我是否在這種情況下錯誤地使用Async / Await? 根據我目前的觀察結果,它沒有按照我的預期進行擴展。 TPL DataFlow會成為我的解決方案嗎?
對於對GetData
的單次調用,嵌套的async / await調用不會引入任何並發。 您檢索所有tierOnes,然后檢索tierOne-#1的所有tierTwos,然后是tierTwo-#1的所有tierThree,依此類推,所有都按順序運行(盡管GetTier * Async方法中可能存在一些並發)。
如果您想要並發請求,那么TPL Dataflow確實是一個更好的解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.