【发布时间】:2014-03-21 14:01:57
【问题描述】:
WebAPI 客户端的HttpClient 生命周期应该是多少?
将HttpClient 的一个实例用于多个调用是否更好?
每个请求创建和处理HttpClient 的开销是多少,如下例所示(取自http://www.asp.net/web-api/overview/web-api-clients/calling-a-web-api-from-a-net-client):
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:9000/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
// New code:
HttpResponseMessage response = await client.GetAsync("api/products/1");
if (response.IsSuccessStatusCode)
{
Product product = await response.Content.ReadAsAsync<Product>();
Console.WriteLine("{0}\t${1}\t{2}", product.Name, product.Price, product.Category);
}
}
【问题讨论】:
-
我不确定,但是您可以使用
Stopwatch类对其进行基准测试。我的估计是拥有一个HttpClient更有意义,假设所有这些实例都在相同的上下文中使用。
标签: c# asp.net web-services asp.net-web-api dotnet-httpclient