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.
- 1.Downloading all files!
- 2.Finished Download File A
- 3.Finished Downloading all files!
- 4.Finished Downloading File B
- 5.Finished Downloading File 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);
}
}
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…