C # downloadasync waiting for download to complete

Can I wait for the download to complete and then execute the next line of code?

WebClient wb = new WebClient();
wb.DownloadFileAsync(new Uri("url"), @"c:\tmp\file.exe");
wb.DownloadProgressChanged += wb_DownloadProgressChanged;
wb.DownloadFileCompleted += wb_DownloadFileCompleted;
//Code to run after download finished...

I know that I can just use wb.DownloadFile, but that will not give feedback on the download.

+3
source share
2 answers

If you are using .net 4.5, you can use new keywords async/awaitand DownloadFileTaskAsync

async void DownloadSomeFile()
{
   WebClient wb = new WebClient();
   wb.DownloadProgressChanged += wb_DownloadProgressChanged;
   wb.DownloadFileCompleted += wb_DownloadFileCompleted;

   await wb.DownloadFileTaskAsync(new Uri("url"), @"c:\tmp\file.exe");

   //Do the other work here
}
+3
source

Yes, you can use the new keyword awaitthat was introduced in .Net 4.5 along with Async methods.

See the MSDN link for how to get code to wait for the download to complete.

+1
source

All Articles