【发布时间】:2016-05-26 07:25:46
【问题描述】:
我正在尝试调用服务,但该服务的每个请求都有最大长度,因此我将我的请求拆分为多个较小的请求。
然后我尝试将 HttpClient 与 Await 一起用作其异步
public async Task<string> CallGenoskanAsync(List<string> requestList)
{
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
var credentials = new NetworkCredential(userId, password);
var tasks = new List<Task<string>>();
foreach (string requestString in requestList)
{
using (HttpClientHandler handler = new HttpClientHandler { Credentials = credentials })
{
using (HttpClient client = new HttpClient(handler))
{
client.BaseAddress = new Uri(baseAddress);
using (HttpResponseMessage response = client.GetAsync(requestString).Result)
using (HttpContent content = response.Content)
{
tasks.Add(content.ReadAsStringAsync());
}
}
}
}
Task.WaitAll(tasks.ToArray());
var result = "";
foreach (var task in tasks)
{
result += task.Result;
}
return result;
}
此代码在调用 await client.GetAsync 时死锁,它永远不会完成。
如果我将该行更改为
using (HttpResponseMessage response = client.GetAsync(requestString).Result)
然后我没有遇到任何死锁,我想我将 await 与 foreach 一起使用不正确,但我不知道如何
编辑:更改示例代码
【问题讨论】:
标签: c# asynchronous dotnet-httpclient