[英]HttpClient multithreading with Content.ReadAsAsync method
Iv been reading alot about HttpClient and realized that I had to change our implementation of our RestHandler due to we were instantiating a new HttpClient object for each request. iv大量阅读了有关HttpClient的内容,并且意识到我不得不更改RestHandler的实现,因为我们为每个请求实例化了一个新的HttpClient对象。 We use alot of request for our RestHandler (using HttpClient).
我们对RestHandler使用很多请求(使用HttpClient)。
Questions: 问题:
Now the implementation looks something like this: 现在实现看起来像这样:
public class RestHandler : IRestHandler
{
private static readonly HttpClient HttpClient = new HttpClient();
public RestHandler()
{
//HttpClient.DefaultRequestHEaders.Authorization = new AuthenticationHeaderValue(some logic);
//HttpClient.DefaultRequestHEaders.Add("id","customId");
}
public async Task<GenericResult<T>> GetResultAsync<T>(string url) where T : new()
{
var response = await HttpClient.GetAsync(url);
var result = await response.Content.ReadAsAsync<T>();
return new GenericResult<T> { HttpResponseMessage = response, Result = result};
}
}
public interface IRestHandler
{
Task<GenericResult<T>> GetResultAsync<T>(string url) where T : new();
}
public class GenericResult<T> where T : new()
{
public T Result { get; set; }
public HttpResponseMessage HttpResponseMessage { get; set; }
}
Best regards Robert 最好的问候罗伯特
Read this: You're using httpClient wrong and it's destabilizing your software 请阅读以下内容: 您错误地使用了httpClient,这破坏了软件的稳定性
It talks about how HttpClient is truly reentrant and thread-safe. 它讨论了HttpClient如何真正可重入和线程安全。 It also proves its case for why you should be using one single HttpClient for the entire application.
这也证明了为什么要在整个应用程序中使用单个HttpClient的情况。
What you're doing looks fine to me. 你在做什么对我来说很好。
As an aside, I've personally had problems with HttpClient and Mono. 顺便说一句,我个人在使用HttpClient和Mono时遇到了问题。 We use RestSharp and prefer it.
我们使用RestSharp并更喜欢它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.