异步下载文件,然后重新同步

本文关键字:同步 新同步 下载 文件 然后 异步 | 更新日期: 2023-09-27 18:04:14

我尝试异步下载某些文件,使用来自MSDN和这里的提示,但我的尝试通常以死锁或由应用程序未等待下载结束引起的错误告终。下面我粘贴了样例代码,不工作,但希望解释我的意图。我将感激你的帮助。

public void SomeMethod() // which must be called synchronously
    {
        // Determine which files to download
    List<FileRequest> fileRequests = Determine();
    var test = DownloadFilesAsync(fileRequests);
    test.Wait();
    // After that do something else with downloaded files synchronously
}
public async Task DownloadFilesAsync(List<FileRequest> fileRequests)
    {
        await Task.WhenAll(fileRequests.Select(fileRequest =>
DownloadFileAsync(fileRequest))).ConfigureAwait(false);
    }
public async Task DownloadFileAsync(FileRequest fileRequest)
    {
        using (WebClient client = new WebClient())
        {
            await client.DownloadFileTaskAsync(fileRequest.url,fileRequest.downloadPath).ConfigureAwait(false);
        }
    }

异步下载文件,然后重新同步

使用test.Wait();会阻塞async方法

使用async的最佳实践是在整个方法中始终使用await

public async Task SomeMethod() {
    // Determine which files to download
    List<FileRequest> fileRequests = Determine();
    //this will allow the down load to not lock the ui
    await DownloadFilesAsync(fileRequests);
    // After that do something else with downloaded files synchronously
    //...
}
public async Task DownloadFilesAsync(List<FileRequest> fileRequests) {
    await Task.WhenAll(fileRequests.Select(fileRequest =>
        DownloadFileAsync(fileRequest))).ConfigureAwait(false);
}
public async Task DownloadFileAsync(FileRequest fileRequest) {
    using (WebClient client = new WebClient()) {
        await client.DownloadFileTaskAsync(fileRequest.url,fileRequest.downloadPath).ConfigureAwait(false);
    }
}

Source - Async/Await -异步编程的最佳实践