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

北城余情 提交于 2019-12-10 03:47:08

问题


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.


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!