Leo*_*ann 0 c# asynchronous webclient task async-await
我正在实现一个方法,以便相互下载多个文件.
我希望Method是异步的,所以我不会阻止UI.
这是下载单个文件的方法,并将Download-Task返回到上级方法,后者下载所有文件(进一步向下).
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);
}
}
Run Code Online (Sandbox Code Playgroud)
在这里,我只是IEnumerable<Task>从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)));
}
Run Code Online (Sandbox Code Playgroud)
最后,我想调用这样的方法:
private void RetrieveUpdate()
{
UpdateInformationDownload.DownloadFiles();
AnalyzeFile();
}
Run Code Online (Sandbox Code Playgroud)
问题是,方法RetrieveUpdate()跳过AnalyzeFile()然后尝试访问目前正在下载的文件.
需要我想能够打电话UpdateInformationDownload.DownloadFiles(),等到它完成(这意味着,它下载了所有文件),然后继续同步AnalyzeFile().
我怎样才能做到这一点?我已经在互联网上查找了大量资源,并找到了几个解释和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);
}
}
Run Code Online (Sandbox Code Playgroud)
没有await,确实:Dispose()立即发生.
我相信roslynator现在会自动检测到这种情况并向您发出警告(并且可以自动修复) - 非常值得安装.
同样:
private async Task RetrieveUpdate()
{
await UpdateInformationDownload.DownloadFiles();
AnalyzeFile();
}
Run Code Online (Sandbox Code Playgroud)
和:
public async Task DownloadFiles() {...}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
94 次 |
| 最近记录: |