HttpClient
WebAPI客户端的生命周期应该是多少?为多个调用
设置一个实例是否更好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);
}
}
Run Code Online (Sandbox Code Playgroud) 我最近创建了一个用于测试HTTP调用吞吐量的简单应用程序,该应用程序可以以异步方式生成,而不是传统的多线程方法.
该应用程序能够执行预定义数量的HTTP调用,最后它显示执行它们所需的总时间.在我的测试期间,所有HTTP调用都发送到我的本地IIS服务器,并且他们检索了一个小文本文件(大小为12个字节).
下面列出了异步实现代码中最重要的部分:
public async void TestAsync()
{
this.TestInit();
HttpClient httpClient = new HttpClient();
for (int i = 0; i < NUMBER_OF_REQUESTS; i++)
{
ProcessUrlAsync(httpClient);
}
}
private async void ProcessUrlAsync(HttpClient httpClient)
{
HttpResponseMessage httpResponse = null;
try
{
Task<HttpResponseMessage> getTask = httpClient.GetAsync(URL);
httpResponse = await getTask;
Interlocked.Increment(ref _successfulCalls);
}
catch (Exception ex)
{
Interlocked.Increment(ref _failedCalls);
}
finally
{
if(httpResponse != null) httpResponse.Dispose();
}
lock (_syncLock)
{
_itemsLeft--;
if (_itemsLeft == 0)
{
_utcEndTime = DateTime.UtcNow;
this.DisplayTestResults();
}
}
} …
Run Code Online (Sandbox Code Playgroud)