Web Api Client in Windows Forms

Asked

Viewed 2,652 times

4

I am making a client using Web Api. My site has the server function of the Web Api. I found this reference from Microsoft http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client that has a client example:

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 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 is the big difference between these two codes. My implementation is acceptable?

Microsoft:

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

My code:

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

1 answer

5


The main difference is that the first option (using await) will not block the thread where it is called from (the compiler will divide the method by 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 answer comes.

If you run the 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 time to arrive, your Windows Forms application will seem "locked" until the answer arrives.

Use .Result works well in command line applications, but for applications with GUI use await is recommended.

  • I found out why await does not work in my case. In the microsoft link is the event call: RunAsync().Wait();. If I do RunAsync(); works. Is there something missing. Another detail of RunAsync();, Because this call is not awaited, Execution of the Current method continues before the call is completed. Consider Applying the 'await' Operator to the result of the call. E: webapi converter Form1.Cs 43 13 converter

  • You can do the method that called the RunAsync() be asynchronous as well (using the modifier async), and with that you can call await RunAsync().

Browser other questions tagged

You are not signed in. Login or sign up in order to post.