Reputation: 82
I tried to download asynchronously certain files, using tips from MSDN and from here, but my attempts usually end with deadlock or errors caused by aplication not waiting for the end of download. Below I pasted sample code that doesn't work but hopefully explains my intentions. I will be grateful for your help.
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);
}
}
Upvotes: 0
Views: 467
Reputation: 246998
Using the test.Wait();
is blocking the async method
Best practice in using async
is to use await
all the way through the method. Don’t mix blocking and async code.
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 - Best Practices in Asynchronous Programming
Upvotes: 1