当我“等待"时一个“异步"的方法变得同步了吗? [英] When I "await" an "async" method does it become synchronous?

查看:87
本文介绍了当我“等待"时一个“异步"的方法变得同步了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是场景:

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而同步运行,还是它们都按照执行顺序异步运行?

Is "someAsyncMethod" and "someOtherAsyncMethod" running synchronously because we are using await, or are they both running asynchronously in the order that they are being executed?

UPDATE

UPDATE

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

Given the answer below stating that the awaited async methods will run sequentially, what would be the purpose of making those method calls asynchronous in the first place if we are just going to stop execution and wait the those method's return values? 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?

推荐答案

它们异步运行,但顺序运行.在someAsyncMethod完成之前,不会调用someOtherAsyncMethod.

They are running asynchronously, but sequentially. someOtherAsyncMethod will not be invoked until someAsyncMethod finishes.

如果要并行运行它们,则有几种选择

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

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

// or

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


后续问题:


Follow-up question:

过去我曾看到本机应用程序使用await/async作为释放UI线程的方法,但是还有其他原因使这种设计更理想吗?

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正在运行-如果这些方法正在运行真正的异步I/O.这基本上是您在ASP.NET应用程序中执行此操作的唯一原因.

In an ASP.NET application, you'll want to use this to allow the current thread to go back to the threadpool and serve other incoming requests, while MethodA/MethodB are running - IF these methods are doing true async I/O. That's basically the only reason why you'd do this in an ASP.NET app.

您可能还想阅读Stephen Cleary的文章:

You might also want to read Stephen Cleary's:

  • Task.Run Etiquette Examples: Don't Use Task.Run in the Implementation
  • There Is No Thread.

这篇关于当我“等待"时一个“异步"的方法变得同步了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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