DownloadFile vs DownloadFileAsync

流过昼夜 提交于 2020-01-01 09:22:24

问题


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?

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: Yes I tried googling and reading, couldn't find the answer I need.


回答1:


Edit: 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");

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

await WebClient.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.

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)




回答2:


client.DownloadFileTaskAsync(new Uri(url), saveLocation).Wait();
// Waiting for download...


来源:https://stackoverflow.com/questions/21009162/downloadfile-vs-downloadfileasync

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!