gpt4 book ai didi

c# - 嵌套的 Async/Await 似乎没有扩展

转载 作者:太空狗 更新时间:2023-10-29 23:50:37 25 4
gpt4 key购买 nike

我有以下(简化的)代码:

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 的所有 tierThrees,依此类推,所有这些都按顺序运行(尽管 GetTier*Async 方法中可能存在一些并发)。

如果你想要并发请求,那么TPL Dataflow确实是一个更好的方案。

关于c# - 嵌套的 Async/Await 似乎没有扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30635462/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com