berk_canc
berk_canc

Reputation: 47

async and await in console app

Given this is the code below I'd expect to see this output:

----- Enter main
----- Exit main
----- 185ms passed

But instead, it acts synchronously and Foo blocks MainAsync from returning. Can anyone clarify?

class Program
{
    static void Main(string[] args)
    {
        MainAsync().GetAwaiter().GetResult();
    }


    static async Task MainAsync()
    {
        Console.WriteLine("----- Enter main");
        await Foo();
        Console.WriteLine("----- Exit main");

        Console.ReadKey();
    }

    public static async Task Foo()
    {
        DateTime time = DateTime.Now;
        HttpClient client = new HttpClient();
        string urlContents = await client.GetStringAsync("http://msdn.microsoft.com");

        Console.WriteLine("----- " + (DateTime.Now - time).Milliseconds + "ms passed");
    }
}

Upvotes: 1

Views: 7640

Answers (1)

Servy
Servy

Reputation: 203821

await Foo(); means that the rest of the method won't run until after the Task returned by Foo has completed. That's what it means to await something; the method won't continue until that Task has completed. As such, Console.WriteLine("----- Exit main"); won't run until after Foo has completed, which won't be until after it has already written out the time it took.

Upvotes: 6

Related Questions