In programs utilizing async-await, my understanding is like this:
- an async method that IS NOT awaited will run in the background (?) and rest of the code will continue to execute before this non-awaited method finishes
- an async method that IS awaited will wait until the method finishes before moving on to the next lines of code
The application below was written by me to check if the above statements are correct.
using System;
using System.Threading.Tasks;
namespace ConsoleApp3
{
class Program
{
static async Task Main(string[] args)
{
Console.WriteLine("Hello World!");
DoJob();
var z = 3;
Console.ReadLine();
}
static async Task DoJob()
{
var work1 = new WorkClass();
var work2 = new WorkClass();
while (true)
{
await work1.DoWork(500);
await work2.DoWork(1500);
}
}
}
public class WorkClass
{
public async Task DoWork(int delayMs)
{
var x = 1;
await Task.Delay(delayMs);
var y = 2;
}
}
}
Here are some of my observations:
- The
DoJob();
call is not awaited. However, the debugger shows me that the code inside of DoJob is being executed, just as if it was a normal non-async method. - When code execution gets to
await work1.DoWork(500);
, I would think "OK, so maybe now theDoJob
method will be left andvar z = 3;
will be executed? After all, 'await' should leave the method." In reality, it just goes intoDoWork
and doesn't leaveDoJob
-var z = 3;
is still not executed. - Finally, when execution reaches
await Task.Delay(delayMs);
,DoJob
is left, and thevar z = 3;
is reached. After that, code after theDelay
is executed.
The things that I don't understand:
- Why does
await Task.Delay(delayMs);
leave theDoJob
method, butawait work1.DoWork(500);
does not? - I see that
DoJob
is executing normally. I thought it would be done in the background (maybe by one of the thread pool threads?). Looks like it could block the thread if it was some long-running method, am I right?