Web Api Client in Windows Forms

4

I'm making a client using Web Api. My site has the Web server function Api. I found this reference from Microsoft link 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 the line below hangs 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's 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;
    
asked by anonymous 05.05.2014 / 20:23

1 answer

5

The main difference is that the first option (using await ) will not block the thread from where it is called (the compiler will split the method by registering a callback in> 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 the code with .Result on the UI thread (for example, in a method called when a button is pressed), and the Web API response is slow to arrive, your Windows Forms application will appear "locked "until the answer arrives.

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

    
06.05.2014 / 15:12