C# 异步下载多个文件并等待所有文件完成,然后再执行其余代码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16514027/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 01:11:48  来源:igfitidea点击:

Download multiple files async and wait for all of them to finish before executing the rest of the code

c#downloadasync-awaitconsole-application

提问by user2100493

I am trying to download multiple files from the internet and await for all of them to finish. This is a C# console application that I am running, so no progress bar event handler should be necessary. However it currently just continues to execute code even though all files have not been downloaded.

我正在尝试从 Internet 下载多个文件并等待所有文件完成。这是我正在运行的 C# 控制台应用程序,因此不需要进度条事件处理程序。但是,即使尚未下载所有文件,它目前也只是继续执行代码。

  • 1.Downloading all files!
  • 2.Finished Download File A
  • 3.Finished Downloading all files!
  • 4.Finished Downloading File B
  • 5.Finished Downloading File C
  • 1.下载所有文件!
  • 2.完成下载文件A
  • 3.完成下载所有文件!
  • 4.完成下载文件B
  • 5.完成下载文件C

How would you await till all async download files are finished.

您将如何等待所有异步下载文件完成。

 private void DownloadMultipleFiles(List<DocumentObject> doclist)
    {
        foreach(var value in doclist){
            try
            {
                using (WebClient webClient = new WebClient())
                {
                    string downloadToDirectory = @Resources.defaultDirectory + value.docName;
                    webClient.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
                    webClient.DownloadFileCompleted += client_DownloadFileCompleted;
                    webClient.DownloadFileAsync(new Uri(value.docUrl), @downloadToDirectory);

                    //Add them to the local
                    Context.listOfLocalDirectories.Add(downloadToDirectory);
                }         
            }
            catch (Exception)
            {
                Errors.printError("Failed to download File: " + value.docName);
            }
        }
    }

采纳答案by Stephen Cleary

The DownloadFileAsync/DownloadFileCompletedmembers of WebClientuse the Event-based Asynchronous Pattern. If you want to use asyncand await, you should be using the Task-based Asynchronous Pattern.

DownloadFileAsync/DownloadFileCompleted的成员WebClient使用基于事件的异步模式。如果你想使用asyncand await,你应该使用基于任务的异步模式

In this case, you should use the DownloadFileTaskAsyncmember, as such:

在这种情况下,您应该使用DownloadFileTaskAsync成员,如下所示:

private async Task DownloadFileAsync(DocumentObject doc)
{
  try
  {
    using (WebClient webClient = new WebClient())
    {
      string downloadToDirectory = @Resources.defaultDirectory + doc.docName;
      webClient.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
      await webClient.DownloadFileTaskAsync(new Uri(doc.docUrl), @downloadToDirectory);

      //Add them to the local
      Context.listOfLocalDirectories.Add(downloadToDirectory);
    }         
  }
  catch (Exception)
  {
    Errors.printError("Failed to download File: " + doc.docName);
  }
}

private async Task DownloadMultipleFilesAsync(List<DocumentObject> doclist)
{
  await Task.WhenAll(doclist.Select(doc => DownloadFileAsync(doc)));
}

Please note that your Context.listOfLocalDirectories.Addand Errors.printErrormethods should be threadsafe.

请注意,您的Context.listOfLocalDirectories.AddErrors.printError方法应该是线程安全的。