.nethttpclient.net-4.5getasync

HttpClient.GetAsync not working


Why is this code not working? I've used similar things earlier which makes it even more confusing. It just exits on "await httpClient.GetAsync..." line without any exception that can be caught in try/catch. I have this same exact code in a sample console app targeting .net 4.5 and testing on two different machines, getting same result (or lack thereof).

EDIT: entire Program.cs sample

using System;
using System.Net.Http;

namespace Main
{
    class Program
    {
        static void Main(string[] args)
        {
            DownloadPageAsync();
        }

        private static async void DownloadPageAsync()
        {
            var httpClient = new HttpClient();
            var response = await httpClient.GetAsync("http://en.wikipedia.org/");
            response.EnsureSuccessStatusCode();
            Console.WriteLine(await response.Content.ReadAsStringAsync());
            httpClient.Dispose();

            Console.ReadLine();
        }
    } 
}

Solution

  • The main thread is ending before the DownloadPageAsync method's completion.

    You are using void in the signature of the method, that means, fire and forget. When you are calling the DownloadPageAsync method inside the Main method, if that runs too fast, it would work just fine, if that takes a little more time, it will end the program before the code gets executed. You should use Task on the DownloadPageAsync and .Result on the Main method to wait for the code to get executed.

    Or, change the Console.ReadLine(); to the main method, instead of the .Result. that should work also if you don't press the enter key :).