HttpClientWebAPI客户端的生命周期应该是多少?为多个调用
设置一个实例是否更好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) 我已经看到了许多类似的问题,但没有找到我的答案.
我的问题是我用以下流程创建线程:
private void btn_Click(object sender, EventArgs e)
{
service.GetCount(
(count, ex) =>
{
if (ex != null)
return;
for (int i = 0; i < count; i++)
{
service.Get(onItemReceived, i);
}
}
);
}
public void GetCount(Action<int, Exception> callback)
{
var callingThread = TaskScheduler.FromCurrentSynchronizationContext();
Func<int> action = () =>
{
return client.GetCount(); // Synchronous method, could take a long time
};
Action<Task<int>> completeAction = (task) =>
{
Exception ex = (task.Exception != null) ? task.Exception.InnerException : task.Exception;
if (callback …Run Code Online (Sandbox Code Playgroud)