我正在处理一个我继承的应用程序,它对API进行异步调用。应用程序向API发送大约60个异步请求,然后在准备好时检索它们。 API以zip存档对象的形式返回结果。它使用以下(缩写)代码从API检索结果,但这会不断抛出System.Threading.Tasks.TaskCanceledException错误
HttpResponseMessage response = client.SendAsync(requestMessage).Result;
Stream responseStream = response.Content.ReadAsStreamAsync().Result;
responseStream.Seek(0, 0);
za = new ZipArchive(responseStream, ZipArchiveMode.Read);
所以我试图通过使用await来解决这个问题,并实现了以下方法,但我仍然遇到了同样的错误。我可以通过网站检查我的API请求的状态,因此我知道它们没有被API取消。失败的请求会在不到5分钟内失败,所以我知道这也不是因为HTTPClient上的超时值太低。这是我在异步编程中的第一次破解,所以如果有人可以帮助解决这个问题,我将不胜感激。感谢。
public async Task<ZipArchive> GetExport(SourceTable sourceTable)
{
ZipArchive zipArchive = null;
switch (GetResultStatus(sourceTable))
{
case null:
break;
case "Completed":
{
zipArchive = await RetrieveResult(sourceTable);
}
break;
}
return zipArchive;
}
private async Task<ZipArchive> RetrieveResult(SourceTable sourceTable)
{
Export export = sourceTable.exports[0];
ZipArchive za = await RetrieveResultAsync(export);
return za;
}
private async Task<ZipArchive> RetrieveResultAsync(Export export)
{
ZipArchive za = null;
var credentials = new NetworkCredential(userName, password);
HttpClientHandler handler = new HttpClientHandler { Credentials = credentials };
HttpClient client = new HttpClient(handler);
client.Timeout.Add(new TimeSpan(0, 5, 0)); //5 minutes
HttpResponseMessage response = await client.GetAsync(restURL + "file/" + export.FileId);
response.EnsureSuccessStatusCode();
Stream responseStream = await response.Content.ReadAsStreamAsync();
responseStream.Seek(0, 0);
za = new ZipArchive(responseStream, ZipArchiveMode.Read);
return za;
}
更新:在为此代码添加更多日志记录后,我发现它确实是一个超时问题,而且我没有正确设置超时值。设置如下所示的值时,它解决了问题(当然设置了比默认值更高的超时值)
var credentials = new NetworkCredential(userName, password);
HttpClientHandler handler = new HttpClientHandler { Credentials = credentials };
HttpClient client = new HttpClient(handler);
client.Timeout = TimeSpan.FromMinutes(httpClientTimeout);