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

时间:2013-05-13 02:15:23

标签: c# download async-await console-application

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

  • 1.下载所有文件!
  • 2.完成下载文件A
  • 3.Finished下载所有文件!
  • 4.Finished Downloading File B
  • 5.Finished Downloading File 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);
            }
        }
    }

1 个答案:

答案 0 :(得分:39)

DownloadFileAsync的{​​{1}} / DownloadFileCompleted成员使用Event-based Asynchronous Pattern。如果您想使用WebClientasync,则应该使用Task-based Asynchronous Pattern

在这种情况下,您应该使用DownloadFileTaskAsync member,因为:

await

请注意,您的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.Add方法应该是线程安全的。