简体   繁体   English

如何将 Webclient.DownloadFileAsync 包装成可等待的方法?

[英]How to wrap Webclient.DownloadFileAsync into an awaitable method?

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 .我想将实际上是非阻塞的WebClient.DownloadFileAsync方法包装到一个返回 Task 的方法中,并且可以等待直到下载完成

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.我理解订阅 DownloadFileCompleted 事件背后的逻辑,正如这里(以及许多其他帖子)所解释的,但我想将它包装成更用户友好的东西。 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我能想到的最好的方法是将 DownloadFile 方法(同步)包装到 Task 中并返回它,但我读过很多次将同步方法包装到异步方法上不是一个好习惯

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谢谢

As per @JonSkeet's comment above, the answer is:根据上面@JonSkeet 的评论,答案是:

  • The method DownloadFileAsync has been thought long before await/async was implemented早在实现 await/async 之前就已经考虑过方法 DownloadFileAsync
  • The method I was looking for is called DownloadFileTaskAsync , a straightforward async file downloader, and there is no need to rewrite a wrapper我正在寻找的方法称为DownloadFileTaskAsync ,一个简单的异步文件下载器,无需重写包装器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM