I have a problem with HttpClient and async requests. Basically, I have an async method that creates asynchronous requests with a common HttpClient that is initialized in ctor.
My problem is that it seems that HttpClient is blocking my method asynchronously when called.
Here is my 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 a method that blocks a common 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 fragment is not blocked when using the 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 generic HttpClient and not? Or can I use it in some other way?
source share