23
votes

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?

1
small sidenote Main cannot use await as its not itself marked as async - Jamiec
My understanding is that someAsyncMethod would entirely finish before someOtherAsyncMethod would start. - Biscuits
@Biscuits Not even that - await has nothing to do with how the methods (or their tasks) are executed; it simply handles what happens when the tasks are completed. I can await an enumerable if I want just by adding a simple extension method. It has nothing to do with threads (and only a little to do with tasks, really). - Luaan
@dcastro thanks for the in-depth follow up! - mdlars
what would be the purpose of making those method calls asynchronous in the first place I wish more people were asking that... Maybe you'll like my standard posts on when to use async IO and why: stackoverflow.com/a/25087273/122718 Why does the EF 6 tutorial use asychronous calls? stackoverflow.com/a/12796711/122718 Should we switch to use async I/O by default? - usr

1 Answers

28
votes

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: