簡體   English   中英

Try-catch不等待內部的異步功能

[英]Try-catch doesn't wait for async function inside

我想做的是,在嘗試下載文件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#6+,請使Try()方法簽名為async並使用await調用。

否則,您需要使用@Denis Krasakov建議的簡單布爾值更改邏輯。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM