1

I'd like to wrap the WebClient.DownloadFileAsync method, which is actually non blocking, into a method which returns a Task and can be awaited until the download is completed.

I understand the logic behind suscribing to the DownloadFileCompleted event, as explained here (and in plenty other posts) but I'd like to wrap it into something more user friendly. And my knowledge of asynchronous programming is quite superficial.

The best I can think of is to wrap DownloadFile method (synchronous) into a Task and returns it , but I've read many times that wrapping a synchronous method onto a an asynchronous one is not a good practice

return Task.Run(() =>client.DownloadFile(fileUri, localPath));

It's actually the first time I meet an async method which is non awaitable, is there a reason why it has been thought this way?

Thanks

XavierAM
  • 1,627
  • 1
  • 14
  • 30
  • 3
    I think you're looking for [`DownloadFileTaskAsync`](https://learn.microsoft.com/en-us/dotnet/api/system.net.webclient.downloadfiletaskasync) – Jon Skeet Oct 14 '19 at 16:34
  • As for why it was designed that way: there have been many models of asynchrony in .NET. This method was introduced in .NET 2, long before `Task` existed. – Jon Skeet Oct 14 '19 at 16:35
  • @JonSkeet that's what I thought but I was wondering why there was no up-to-date method. As per your answer, there is one. Thanks. Do you want to write an answer or shall I do it? I am a big fan of your books btw ;-) – XavierAM Oct 14 '19 at 16:37

1 Answers1

2

As per @JonSkeet's comment above, the answer is :

  • The method DownloadFileAsync has been thought long before await/async was implemented
  • The method I was looking for is called DownloadFileTaskAsync, a straightforward async file downloader, and there is no need to rewrite a wrapper
XavierAM
  • 1,627
  • 1
  • 14
  • 30