23

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

  • 1.下载所有文件!
  • 2.完成下载文件A
  • 3.完成所有文件的下载!
  • 4.完成下载文件B
  • 5.完成下载文件C

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

 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);
            }
        }
    }
4

1 回答 1

52

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

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

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)));
}

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

于 2013-05-13T03:27:48.240 回答