2

Experimenting with WebClient.DownloadFileAsync:

public void DownloadFile(string fileUrl, string localFile)
{
    using (WebClient client = new WebClient())
    {
        downloadingFile = true;
        client.DownloadFileCompleted += client_DownloadFileCompleted;
        client.DownloadFileAsync(new Uri(fileUrl), localFile);

        while (downloadingFile) { };
    }
}

private void client_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
    downloadingFile = false;
}

Problem is that the DownloadFileCompleted event is never fired, so I never set downloadingFile = false => the while loop never finishes.

Any ideas for what is going wrong?

Thanks!

Louisa
  • 552
  • 1
  • 9
  • 22

2 Answers2

1

This seems to be a logical mistake (kind of deadlock situation) because your main thread is on continuous loop over a condition and never gets time to raise event even if the download is completed.

Solution#1: Remove the while (downloadingFile) { }; line to release the main thread, if you want to hold the control flow you can make your method DownloadFile async and use following line of code to awaitable varient of DownloadFile method.

await client.DownloadFileTaskAsync(new Uri(fileUrl), localFile);
Asad Mehmood
  • 135
  • 8
0

You have to return an instance of type AsyncCompletedEventHandler from your eventhandler (Client_DownloadFileCompleted) and not void.

See MSDN link for more details.

Martin
  • 644
  • 5
  • 11