共享HttpClient阻止异步请求

时间:2013-07-01 07:46:53

标签: c# .net multithreading asynchronous

我遇到了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是不是?或者我可以用其他方式利用它吗?

1 个答案:

答案 0 :(得分:2)

实际上建议使用共享HttpClient

请参阅我的回答为什么 - What is the overhead of creating a new HttpClient per call in a WebAPI client?