Home > Back-end >  Understanding "await" usage in async methods
Understanding "await" usage in async methods

Time:10-11

I'm running the following code:

using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using System.Threading;

public class Program
{
    public static void Main()
    {
        new Program().Test();
    }
        
    public async Task Test() 
    {
        Console.WriteLine("starting...");
        await Test2();
        Console.WriteLine("done!");
        Thread.Sleep(2*1000);
    }
        
    public async Task Test2() 
    {
        Console.WriteLine("Task in delay...");
        await Task.Delay(5000);
    }
            
}

I was expecting the output to be:

starting...
task in delay...
done!

However, when I run the code, I get:

starting...
Task in delay...

and the program terminates. Am I missing something? How should I modify the code to get the expected result?

Another question - according to my understanding, using await is redundant on the last line in a method, if I remove it, how can I await on the method?

CodePudding user response:

Am I missing something?

Yes; you didn't await Test

    public static async Task Main()
    {
        await new Program().Test();
    }

Without that, Main would finish immediately as soon as Test returns, which will be the first time an incomplete await is encountered - the async chain unwinds from the Task.Delay (which will be incomplete), leaving the rest of the work in Test/Test2 scheduled in the background; since there are no remaining non-background threads, the process exits.

Note that you could also remove the async and just return the task, i.e.

    public static Task Main()
        => new Program().Test();

which will work very similarly, although it changes the semantics a little re synchronous exceptions. If in doubt: await.

  • Related