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.
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.
来源:https://stackoverflow.com/questions/4745553/detecting-connection-drops-while-webclient-is-downloading-a-file-asynchronously