Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shared HttpClient blocks on async requests

I'm having an issue with HttpClient and async requests. Basically i'm having an async method that is creating async requests with a shared HttpClient that is initialized in the ctor.

My problem is that it seems that the HttpClient blocks when calling my method in an async manner.

Here is my calling code:

var tasks = trips.Select(u => api.Animals.GetAsync(u * 100, 100).ContinueWith(t =>
        {
            lock (animals)
            {
                if (t.Result != null)
                {
                    foreach (var a in t.Result)
                    {
                        animals.Add(a);
                    }
                }
            }
        }));
        await Task.WhenAll(tasks);

Here is the method that blocks with a shared HttpClient:

 //HttpClient blocks on each request
                var uri = String.Format("animals?take={0}&from={1}", take, from);
                var resourceSegmentUri = new Uri(uri, UriKind.Relative);

                var response = await _client.GetAsync(resourceSegmentUri);

                if (response.IsSuccessStatusCode)
                {
                    var content = await response.Content.ReadAsStringAsync();

                    var animals = JsonConvert.DeserializeObject<T>(content);

                    return animals;
                }

This snippet does not block, when using a client for each request:

using (var client = new HttpClient(){BaseAddress = new Uri(_config.BaseUrl)})
{
    var uri = String.Format("animals?take={0}&from={1}", take, from);
    var resourceSegmentUri = new Uri(uri, UriKind.Relative);

    var response = await client.GetAsync(resourceSegmentUri);

    if (response.IsSuccessStatusCode)
    {
        var content = await response.Content.ReadAsStringAsync();

        var animals = JsonConvert.DeserializeObject<T>(content);

        return animals;
    }
}

Is a shared HttpClient a no go? Or can I utilize it in some other way?

like image 523
Bj Blazkowicz Avatar asked Nov 02 '22 19:11

Bj Blazkowicz


1 Answers

Using a shared HttpClient is actually recommended.

See my answer why - What is the overhead of creating a new HttpClient per call in a WebAPI client?

like image 164
Dave Black Avatar answered Nov 15 '22 05:11

Dave Black