c# – Client Web API in Windows Forms

Question:

I'm making a client using Web Api. My site has the Web Api server role. I found this Microsoft reference http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client which has an example client:

static async Task RunAsync()
{
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri("http://localhost:9000/");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        // HTTP GET
        HttpResponseMessage response = await client.GetAsync("api/products/1");
        if (response.IsSuccessStatusCode)
        {
            Product product = await response.Content.ReadAsAsync<Product>();
            Console.WriteLine("{0}\t${1}\t{2}", product.Name, product.Price, product.Category);
        }...

The interesting thing is that in the line below it crashes and dies:

HttpResponseMessage response = await client.GetAsync("api/products/1");

Searching the internet, I implemented this code that works:

static async Task RunAsync()
{
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri("http://localhost:17694/");
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        // HTTP GET
        HttpResponseMessage response = client.GetAsync("api/Integracao/GetAllProducts/").Result;
        if (response.IsSuccessStatusCode)
        {
            var product = response.Content.ReadAsStringAsync();
            var dados = JsonConvert.DeserializeObject<List<TipoPessoa>>(product.Result);                     
        }
        else
        {
            Console.WriteLine("Error");
        }
    }
}

My question is, what is the big difference between these two codes. Is my implementation acceptable?

Microsoft:

HttpResponseMessage response = await client.GetAsync("api/products/1");

My code:

HttpResponseMessage response = client.GetAsync("api/Integracao/GetAllProducts/").Result;

Answer:

The main difference is that the first option (using await ) will not block the thread from which it is called (the compiler will split the method, registering a callback to be called when the result of the operation is available), while the second (using .Result ) will block the thread until the response arrives.

If you run code with .Result in the UI thread (for example, in a method called when a button is pressed), and the response from the Web API takes a while to arrive, your Windows Forms application will appear to "hang" until the answer arrive.

Using .Result works fine in command line applications, but for GUI applications using await is recommended.

Scroll to Top