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?
Async/await helps you write synchronous-looking JavaScript code that works asynchronously. Await is in an async function to ensure that all promises that are returned in the function are synchronized. With async/await, there's no use of callbacks.
The async keyword turns a method into an async method, which allows you to use the await keyword in its body. When the await keyword is applied, it suspends the calling method and yields control back to its caller until the awaited task is complete.
In synchronous operations tasks are performed one at a time and only when one is completed, the following is unblocked. In other words, you need to wait for a task to finish to move to the next one. In asynchronous operations, on the other hand, you can move to another task before the previous one finishes.
The call to the async method starts an asynchronous task. However, because no Await operator is applied, the program continues without waiting for the task to complete. In most cases, that behavior isn't expected.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With