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

Async/Task/Await: Await does not actually wait

我正在实施一种方法,以便依次下载多个文件。

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

这是下载单个文件的方法和 return 上级方法的下载任务,它下载所有文件(进一步向下)。

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().

我怎样才能做到这一点?我已经在 Internet 上查找了大量资源并找到了一些解释和 Microsoft Docs,但我认为我没有逐步完成使用 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() {...}