Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DownloadFile vs DownloadFileAsync

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.

like image 805
Reousa Asteron Avatar asked Jan 09 '14 00:01

Reousa Asteron


1 Answers

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)

like image 58
i3arnon Avatar answered Nov 11 '22 12:11

i3arnon