Use of await keyword in c#

I have a doubt. I have read that await keyword is used when we want to wait for a particular function to finish the operation.

public async void Work()
{
await SlowTask();
Console.WriteLine("Execution completed");
}

Now as per the definition, when Work() method is called, it will wait for SlowTask() method to complete its execution before printing "Execution completed". But I have a doubt that even if the await and async keyword are not used then also Work() method is going to wait for SlowTask() method to complete its execution before printing "Execution completed" because it will be executed line by line.

Jon Skeet
people
quotationmark

But I have a doubt that even if the await and async keyword are not used then also Work() method is going to wait for SlowTask() method to complete its execution before printing "Execution completed" because it will be executed line by line.

If you don't use await, it will wait for the SlowTask method to return - but it won't wait for it to complete. This is one of the trickiest aspects of understanding async/await: an async method returns as soon as it needs to await something that hasn't finished, but then it continues when that has completed.

So suppose SlowTask is:

async Task SlowTask()
{
    Console.WriteLine("A");
    await Task.Delay(5000);
    Console.WriteLine("B");
    await Task.Delay(5000);
    Console.WriteLine("C");
}

This method will print A as soon as it's called, but will return when it hits the first await, because the delay won't have been completed. If you don't await SlowTask in your calling code, you'll then see "Execution completed" even though SlowTask hasn't really completed.

After the first delay has completed, SlowTask will resume, and B will be printed. It will return again (to whatever scheduled the continuation) due to the second delay, then continue and print C before completing. If you've actually awaited the task returned by SlowTask that's when you'll see "Execution completed" printed - which is probably what you want.

people

See more on this question at Stackoverflow