简体   繁体   中英

C# DownloadSync event not fired

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!

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

See MSDN link for more details.

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM