我正在尝试从互联网上下载多个文件并等待所有这些文件完成。这是我正在运行的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);
}
}
}
答案 0 :(得分:39)
DownloadFileAsync
的{{1}} / DownloadFileCompleted
成员使用Event-based Asynchronous Pattern。如果您想使用WebClient
和async
,则应该使用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
方法应该是线程安全的。