使用 Content.ReadAsAsync 方法的 HttpClient 多线程
HttpClient multithreading with Content.ReadAsAsync method
我阅读了很多有关 HttpClient 的内容,并意识到我必须更改 RestHandler 的实现,因为我们要为每个请求实例化一个新的 HttpClient 对象。我们对 RestHandler 使用了很多请求(使用 HttpClient)。
问题:
- 我读到 HttpClient 上的几个(全部?)方法是线程安全的,这是否意味着我下面的代码不会有任何线程问题,尽管我使用 Content.ReadAsAsync?
- 以这种方式使用 HttpClient 是否还有其他已知问题?
现在的实现看起来像这样:
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; }
}
此致
罗伯特
读这个:
You're using httpClient wrong and it's destabilizing your software
它讨论了 HttpClient 如何真正实现可重入和线程安全。它还证明了为什么您应该为整个应用程序使用一个 HttpClient。
我觉得你做的很好。
顺便说一句,我个人在使用 HttpClient 和 Mono 时遇到过问题。我们使用 RestSharp 并且更喜欢它。
我阅读了很多有关 HttpClient 的内容,并意识到我必须更改 RestHandler 的实现,因为我们要为每个请求实例化一个新的 HttpClient 对象。我们对 RestHandler 使用了很多请求(使用 HttpClient)。
问题:
- 我读到 HttpClient 上的几个(全部?)方法是线程安全的,这是否意味着我下面的代码不会有任何线程问题,尽管我使用 Content.ReadAsAsync?
- 以这种方式使用 HttpClient 是否还有其他已知问题?
现在的实现看起来像这样:
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; }
}
此致 罗伯特
读这个: You're using httpClient wrong and it's destabilizing your software
它讨论了 HttpClient 如何真正实现可重入和线程安全。它还证明了为什么您应该为整个应用程序使用一个 HttpClient。
我觉得你做的很好。
顺便说一句,我个人在使用 HttpClient 和 Mono 时遇到过问题。我们使用 RestSharp 并且更喜欢它。