srv8
srv8

Reputation: 53

Correct way to create a new task and call asynchronously a web api c#

Hello i have created two examples but i am not sure if any of these are correct. I want to create a new task and call asynchronously a web api c#.Below there are both of the examples.

The first example:

        private string APIResponse()
        {
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("http://localhost:55517/");
            // Add an Accept header for JSON format.  
            client.DefaultRequestHeaders.Accept.Add(new 
               MediaTypeWithQualityHeaderValue("application/json"));

            HttpResponseMessage response = client.GetAsync("api/Values").Result;   
            if (response.IsSuccessStatusCode)
            {
                var products = response.Content.ReadAsStringAsync().Result;
                //Thread.Sleep(5000);
                return products.ToString();
            }
            else
            {
                return "ERROR";
            }
        }

        protected async void Apibtn_Click(object sender, EventArgs e)
        {
            Task<string> task = new Task<string>(APIResponse);
            task.Start();

            var ApiResp = await task;
            Do some work here... 
            // ...
            //..
            //.
        }

And the second example is :

    private async Task<string> APIResponse()
    {
        HttpClient client = new HttpClient();
        client.BaseAddress = new Uri("http://localhost:55517/");
        // Add an Accept header for JSON format.  
        client.DefaultRequestHeaders.Accept.Add(new 
                MediaTypeWithQualityHeaderValue("application/json"));

        HttpResponseMessage response = await client.GetAsync("api/Values");
        if (response.IsSuccessStatusCode)
        {
            var products = await response.Content.ReadAsStringAsync();
            //Thread.Sleep(5000);
            return products.ToString();
        }
        else
        {
            return "ERROR";
        }
    }

    protected async void Apibtn_Click(object sender, EventArgs e)
    {
        Task<string> task = APIResponse();
        // task.Start();  //You don't need to start the Tasks returned by 
                            async method calls. They're started by default.

        var ApiResp = await task;
        //Do some work here... 
        //...
        //..
        //.
    }

If none of the above is correct could you please give me an example? Thanks!

Upvotes: 2

Views: 1821

Answers (2)

Camilo Terevinto
Camilo Terevinto

Reputation: 32058

Your second example is almost correct, just do something like this instead:

private async Task<string> APIResponse()
{
    using (HttpClient client = new HttpClient())
    {
        ...
        HttpResponseMessage response = await client.GetAsync("api/Values");
        ...
    }
}

protected async void Apibtn_Click(object sender, EventArgs e)
{
    var apiResp = await APIResponse();
}

Don't forget the using statement on IDisposable members (such as HttpClient)

Upvotes: 5

SLaks
SLaks

Reputation: 887275

The second example is correct; you should never use Task.Result.

However, there is no need for a separate task variable at the end; you can await the call directly.

Upvotes: 4

Related Questions