How to deal with exceptions when using WebClient.DownloadFileAsync

后端 未结 3 1810
春和景丽
春和景丽 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:29

    What you can do is create a Task (an async operation) and use the ContinueWith directive to handle the exception. This can be a bit unreadable

    using (WebClient wc = new WebClient())
    {
        wc.DownloadFileCompleted += ((sender, args) =>
        {
            if (args.Error == null)
            {
                File.Move(filePath, Path.ChangeExtension(filePath, ".jpg"));
                mr.Set();
            }
            else
            {
                //how to pass args.Error?
            }
        });
        Task.Factory.StartNew(() => wc.DownloadFile(
                                     new Uri(string.Format("{0}/{1}",
                                     Settings1.Default.WebPhotosLocation,
                                     Path.GetFileName(f.FullName))), filePath))
                    .ContinueWith(t => Console.WriteLine(t.Exception.Message));
    }
    

    However, with the introduction of .NET 4.5, Webclient exposes a task based async download for you!

    using (WebClient wc = new WebClient())
    {
        wc.DownloadFileCompleted += ((sender, args) =>
        {
            if (args.Error == null)
            {
                File.Move(filePath, Path.ChangeExtension(filePath, ".jpg"));
                mr.Set();
            }
            else
            {
                //how to pass args.Error?
            }
        });
        wc.DownloadFileTaskAsync(new Uri(string.Format("{0}/{1}",
                                     Settings1.Default.WebPhotosLocation,
                                     Path.GetFileName(f.FullName))),
                                     filePath)
          .ContinueWith(t => t.Exception.Message)
    }
    

提交回复
热议问题