mdlars
mdlars

Reputation: 929

When I "await" an "async" method does it become synchronous?

So here is the scenario:

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;
}

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

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?

Upvotes: 24

Views: 5251

Answers (1)

dcastro
dcastro

Reputation: 68750

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

If you want to run them in parallel, you have several options

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:

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?

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.

You might also want to read Stephen Cleary's:

Upvotes: 29

Related Questions