简体   繁体   English

共享HttpClient阻止异步请求

[英]Shared HttpClient blocks on async requests

I'm having an issue with HttpClient and async requests. 我遇到了HttpClient和异步请求的问题。 Basically i'm having an async method that is creating async requests with a shared HttpClient that is initialized in the ctor. 基本上我有一个异步方法,即使用在ctor中初始化的共享HttpClient创建异步请求。

My problem is that it seems that the HttpClient blocks when calling my method in an async manner. 我的问题是,当以异步方式调用我的方法时,似乎HttpClient阻塞。

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阻塞的方法:

 //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? 共享的HttpClient是不行的? Or can I utilize it in some other way? 或者我可以用其他方式利用它吗?

Using a shared HttpClient is actually recommended. 实际上建议使用共享的HttpClient

See my answer why - What is the overhead of creating a new HttpClient per call in a WebAPI client? 请参阅我的答案为什么 - 在WebAPI客户端中每次调用创建一个新的HttpClient的开销是多少?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM