当 WebClient 异步下载文件时检测连接丢失(在 C# 中)
我正在使用 WebClient 的 DownloadFileAsync (在 C# 中)方法异步下载文件。我将事件处理程序附加到 DownloadProgressChanged 和 DownloadFileCompleted 事件。我希望通过 DownloadFileCompleted 事件处理程序中的 AsyncCompletedEventArgs 的 Error 属性收到任何错误通知。如果在下载开始之前不存在连接,则效果很好。它因适当的错误而崩溃,并且我在上面提到的属性中得到了错误。但是,如果在下载过程中连接断开,则不会发生任何情况。事件处理程序不会被调用,它会永远等待。遇到这种情况我该怎么办? 谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
执行您所要求的操作的最佳方法可能是实现您自己的呼叫超时。
基本上,创建一个计时器,每次触发 DownloadProgressChanged 事件时都会重置该计时器。这样,如果您在超时期限内没有收到任何进度更新,您可以在 WebClient 上调用 CancelAsync 命令,这样您就不必永远等待。
这是我能够做到的唯一方法。
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.