Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

detecting connection drops while WebClient is downloading a file asynchronously (in C#)

I am using WebClient's DownloadFileAsync (in C#) method to download files asynchronously. I have event handlers attached to DownloadProgressChanged and DownloadFileCompleted events. I hoped to get notified of any errors through AsyncCompletedEventArgs's Error property in the DownloadFileCompleted event handler. It works well if the connection is not present before the download begins. It craps out with proper error and I get the error in the property I mentioned above. But if the connection drops while the download is in progress nothing happens. The event handler is not called, it keeps waiting forever. What should I do to handle such a scenario ? Thanks.

like image 715
Ramki Avatar asked Jan 20 '11 09:01

Ramki


1 Answers

The best way to do what you're asking is probably to implement your own timeout for the call.

Basically, create a timer that gets reset every time the DownloadProgressChanged event gets fired. That way, if you don't get any progress updates within your timeout period, you can call the CancelAsync command on the WebClient so you're not waiting around forever.

That's the only way I've been able to do it.

like image 139
Aron Avatar answered Oct 16 '22 02:10

Aron