2

I have written the following (a plain Console application) to test my understanding about async and await in C#.

public class Program
{
    public static void Main(string[] args)
    {
        Console.WriteLine("Async result: " + getLengthFromWebsiteAsync());
    }

    public static async Task<int> getLengthFromWebsiteAsync()
    {
        HttpClient httpClient = new HttpClient();
        Task<string> sampleTask = httpClient.GetStringAsync("http://www.adobe.com");

        Console.WriteLine("Before the await: ");

        int lengthRequired = (await sampleTask).Length;
        Console.WriteLine("After the await: " + lengthRequired.ToString());
        return lengthRequired;
    }

The following is the result that I got upon running:

Before the await:
Async result: System.Threading.Tasks.Task'1[System.Int32]

My question is, isn't the line "After the await: " supposed to show up? Am I on the wrong track in understanding the flow of async/await?

Roy
  • 507
  • 10
  • 22
  • You still have to `await getLengthFromWebsiteAsync()`. Async in a console app is a bit tricky though, see [Async on main method of console app](http://stackoverflow.com/q/9208921/247702). – user247702 Jun 16 '14 at 18:16
  • 3
    You're too happy too early. Ask for the task's Result. – Hans Passant Jun 16 '14 at 18:19

1 Answers1

8

Currently you're starting the operation - but it's never completing. Your program is terminating before you do anything with the task.

As this is a console app, continuations will run on a thread-pool thread anyway, so you can change your code to make the Main method block until the task has completed:

public static void Main(string[] args)
{
    Console.WriteLine("Async result: " + getLengthFromWebsiteAsync().Result);
}

Normally you should be very careful about using Result and Wait() on tasks, as you can easily cause a deadlock. (For example, it wouldn't be safe to do the above in a WinForms UI - the Result call would block the UI thread until the task completed... and the task would be waiting for the UI thread to become available to run the continuation after the await in the async method.)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194