我想做的是,在重试下载文件 5 次后,如果由于某种原因下载失败,重置整个过程并返回第一步:函数 Try()
。如果成功,则继续 ProcessSet(3);
行
但在我的情况下,它开始下载,无需等待,就进入 ProcessSet(3);
行。
我做错了什么?为什么 try
之后的后续步骤不等待 await webClient.DownloadFileTaskAsync(new Uri(response.Url), zip_path);
完成?
这是代码:
using (WebClient webClient = new WebClient())
{
webClient.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
try
{
await webClient.DownloadFileTaskAsync(new Uri(response.Url), zip_path);
}
catch (Exception e)
{
Thread.Sleep(DelayOnRetry);
Try();
}
}
SetProgressBar(40, ProgressBarStyle.Continuous);
ProcessSet(3);
这是 Try()
函数
private void Try()
{
ClearFolder(root_dir);
Directory.CreateDirectory(root_dir);
main_timer.Enabled = false;
ProcessSet(1);
}
这是完整的代码:
https://gist.github.com/turalus/8c781b5b0c56f66f7ec17e66a3e120fc
最佳答案
我建议您更改重试逻辑:
var isFileDownloaded = false;
var tryCount = 0;
while (tryCount++ < MAX_TRY_COUNT && !isFileDownloaded) {
using (WebClient webClient = new WebClient())
try{
//do stuff here
isFileDownloaded = true
}catch //log exception and Thread.Sleep
}
if (isFileDownloaded){
// update progress
} else{
//too many retries, exit app
}
关于c# - Try-catch 不等待内部的异步函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43090351/