Async/Task/Await:Await 实际上并不等待



我正在实现一种方法,以便彼此下载多个文件。

我希望该方法是异步的,这样我就不会阻止 UI。

这是下载单个文件并将下载任务返回到上级方法的方法,该方法会下载所有文件(进一步向下(。

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

在这里,我只是从FilesToDownload中的所有文件创建一个IEnumerable<Task>

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

最后,我想像这样调用该方法:

private void RetrieveUpdate()
{
UpdateInformationDownload.DownloadFiles();
AnalyzeFile();
}

问题是,该方法RetrieveUpdate()跳过AnalyzeFile(),然后尝试访问当前正在下载的文件。

需要我希望能够调用UpdateInformationDownload.DownloadFiles(),等到它完成(这意味着它下载了所有文件(,然后继续与AnalyzeFile()同步。

我怎样才能做到这一点?我已经在互联网上查找了大量资源,并找到了几种解释和Microsoft文档,但我认为我没有逐步完成使用 async/await 的方案。

很简单:await吧!

public aysnc Task DownloadFromRepo(String fileName)
{
...
using (WebClient FileClient = new WebClient())
{
...
await FileClient.DownloadFileTaskAsync(new System.Uri(RepoDir + fileName), 
curFilePath);
}
}

没有await,确实:Dispose()立即发生。

我相信 roslynator 现在会自动检测到这种情况并警告您(并且有可用的自动修复( - 非常值得安装。

同样:

private async Task RetrieveUpdate()
{
await UpdateInformationDownload.DownloadFiles();
AnalyzeFile();
}

和:

public async Task DownloadFiles() {...}

最新更新