How to deal with exceptions when using WebClient.DownloadFileAsync

后端 未结 3 1799
春和景丽
春和景丽 2020-12-11 17:53

I am downloading some files from the internet using a WebClient in the following way:

try  
{
   ManualResetEvent mr = new ManualResetEvent(fals         


        
3条回答
  •  有刺的猬
    2020-12-11 18:22

    You should use await and DownloadFileTaskAsync:

    try  
    {
    
       using (WebClient wc = new WebClient())
       {
    
             await  wc.DownloadFileTaskAsync(new Uri(string.Format("{0}/{1}", Settings1.Default.WebPhotosLocation, Path.GetFileName(f.FullName))), filePath);
    
        }
    }
    catch (Exception ex)
    {
       //Catch my error here and handle it (display message box)
    }
    

    DownloadFileAsync uses Event-based Asynchronous Pattern, you can't catch the exception, you can get exception throw AsyncCompletedEventArgs.Error Property

提交回复
热议问题