本文介绍了DownloadFile与DownloadFileAsync的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用WebClient.DownloadFile一次从Web服务器下载单个文件,但是,我想知道是否通过线程被阻止"开发人员意味着应用程序将没有响应?

I'm using WebClient.DownloadFile to download a single file at a time from a web server, however, I want to know if by "The thread is blocked" developers mean that the application won't be responsive?

我尝试使用WebClient.DownloadFileAsync,但是它不能像DownloadFile一样工作,请澄清一下,由于我正在从网络上下载文件,所以我无法分辨,所以非常感谢立即下载.

I tried using WebClient.DownloadFileAsync but it doesn't work like DownloadFile works, please clarify, and I can't tell because I'm downloading files off my network, so it pretty much downloads instantly, thanks in advance.

PS:是的,我尝试谷歌搜索和阅读,找不到我需要的答案.

PS: Yes I tried googling and reading, couldn't find the answer I need.

推荐答案

WebClient.DownloadFileAsync 以"Async"结尾,但不返回任务.它是基于事件的异步模式的一部分,因此我的回答与之无关.这是一个:您需要订阅 WebClient.DownloadFileCompleted 事件以了解异步操作何时完成.例如:

WebClient.DownloadFileAsync ends with "Async" but doesn't return a task. It's part of the Event-based Asynchronous Pattern so my answer isn't relevant. This one is: You need to subscribe to WebClient.DownloadFileCompleted event to know when the async operation completed. For example:

var client = new WebClient();
var uri = new Uri(address);

client.DownloadFileCompleted += (sender, e) => Console.WriteLine("Finished");
client.DownloadFileAsync(uri, "Hamsters.txt");

原始答案: WebClient.DownloadFileAsync 返回您需要等待的任务.像这样:

Original Answer:WebClient.DownloadFileAsync returns a task you need to await. like so:

await WebClient.DownloadFileAsync(...)

DownloadFileAsync 是触发异步操作并返回在操作结束时将完成的任务. await 表示等待该任务以异步方式结束,因此,当您得到 DownloadFileAsync 的结果时,它将运行该代码.

DownloadFileAsync is fires an asynchronous operation and returns a task that will complete when the operation ended. await means waiting for that task to end in an asynchronous way, so the code after it will run when you have the result of DownloadFileAsync.

同步 DownloadFile 将阻止调用它的线程.如果它是UI线程,那么是的...您的应用将不会响应.如果它不是UI线程,那么它仍将是响应式的,但可扩展性较差(这意味着它使用线程等待而不是做工作,因此您的应用程序总体上可以在相同数量的线程下做更少的事情)

The synchronic DownloadFile will block the thread that called it. If it's the UI thread, then yes... your app won't be responsive. If it isn't the UI thread, then it will still be responsive but it will be less scalable (meaning it uses threads to wait instead of doing work, so your application as a whole can do less with the same amount of threads)

这篇关于DownloadFile与DownloadFileAsync的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-13 13:25