我遇到了 HttpClient 和异步请求的问题。基本上,我有一个异步方法,它使用在 ctor 中初始化的共享 HttpClient 创建异步请求。
我的问题是,当以异步方式调用我的方法时,HttpClient 似乎阻塞了。
这是我的调用代码:
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);
这是使用共享 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;
}
当对每个请求使用客户端时,此代码段不会阻塞:
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;
}
}
共享HttpClient
是不行的吗?或者我可以以其他方式使用它吗?