gpt4 book ai didi

c# - 当我使用 "await" "async"方法时,它会变成同步的吗?

转载 作者:IT王子 更新时间:2023-10-29 04:30:49 25 4
gpt4 key购买 nike

场景是这样的:

static async void Main(string[] args) 
{
await AnAsyncMethod();
}

private static async task<bool> AnAsyncMethod()
{
var x = await someAsyncMethod();
var y = await someOtherAsyncMethod();

return x == y;
}

“someAsyncMethod”和“someOtherAsyncMethod”是因为我们使用 await 而同步运行,还是它们都按照执行顺序异步运行?

更新

鉴于下面的答案表明等待的异步方法将按顺序运行,如果我们只是要停止执行并等待这些方法的返回值,那么首先使这些方法调用异步的目的是什么?我过去曾看到 native 应用程序使用 await/async 作为释放 UI 线程的方法,但是还有其他原因可以说明这种设计是可取的吗?

最佳答案

它们异步运行,但顺序运行someOtherAsyncMethodsomeAsyncMethod 完成之前不会被调用。

如果您想并行运行它们,您有多种选择

var taskA = MethodA();
var taskB = MethodB();

var a = await taskA;
var b = await taskB;

// or

var results = await Task.WhenAll(MethodA(), MethodB());

后续问题:

I have seen native apps in the past use await/async as a means to free up the UI thread, but are there any other reasons why this design would be desirable?

在 ASP.NET 应用程序中,您需要使用它来允许当前线程返回到线程池并为其他传入请求提供服务,而 MethodA/MethodB are running - 如果这些方法正在执行真正的异步 I/O。这基本上是您在 ASP.NET 应用程序中执行此操作的唯一原因。

您可能还想阅读 Stephen Cleary 的:

关于c# - 当我使用 "await" "async"方法时,它会变成同步的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32482275/

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