I am implementing a method in order to Download multiple files after each other.
I want the Method to be async so I dont block the UI.
This is the Method to Download a single file and return the Download-Task to the superior Method, which downloads all files (further down).
public Task DownloadFromRepo(String fileName)
{
// Aktuellen DateiNamen anzeigen, fileName publishing for Binding
CurrentFile = fileName;
// Einen vollqualifizierten Pfad erstellen, gets the path to the file in AppData/TestSoftware/
String curFilePath = FileSystem.GetAppDataFilePath(fileName);
// Wenn die Datei auf dem Rechner liegt, wird sie vorher gelöscht / Deletes the file on the hdd
FileSystem.CleanFile(fileName);
using (WebClient FileClient = new WebClient())
{
FileClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler((s, e) =>
{
Progress++;
});
// Wenn der Download abgeschlossen ist.
FileClient.DownloadFileCompleted += new System.ComponentModel.AsyncCompletedEventHandler((s, e) =>
{
});
// Den DOwnload starten
return FileClient.DownloadFileTaskAsync(new System.Uri(RepoDir + fileName), curFilePath);
}
}
In here, I just create an IEnumerable<Task>
from all the Files in FilesToDownload.
public async void DownloadFiles()
{
// Angeben, dass der Download nun aktiv ist / Show active binding
Active = true;
// Den Fortschritt zurücksetzen / Set Progress to 0 (restarting download)
Progress = 0;
// Die bereits heruntergeladenen Dateien schließen. / Clear Downloads
DownloadedFiles.Clear();
// Alle Downloads starten und auf jeden einzelnen warten
await Task.WhenAll(FilesToDownload.Select(file => DownloadFromRepo(file)));
}
And finally, I want to call the method like this:
private void RetrieveUpdate()
{
UpdateInformationDownload.DownloadFiles();
AnalyzeFile();
}
Problem is, that the Method RetrieveUpdate()
skips AnalyzeFile()
and then tries to access the files, which are being downloaded at the moment..
NEED I want to be able to call UpdateInformationDownload.DownloadFiles()
, wait until it completed (that means, it downloaded all the files) and THEN continue in sync with AnalyzeFile()
.
How can I achieve that? I already looked up plenty of resources on the internet and found several explanations and Microsoft Docs, but I think I didnt step through the scheme of using async/await.