【问题标题】:Event to find when internet is lost寻找互联网丢失时的事件
【发布时间】:2013-07-11 11:31:34
【问题描述】:

我正在使用 C# 创建一个 Windows 应用程序。它用于检查产品的任何更新版本是否可用。如果是,用户可以只使用应用程序的 UI 下载它,而无需打开任何浏览器。

应用程序中的一个窗口使用 ProgressBar 控件显示下载状态。问题是,万一互联网断开连接,应用程序不会知道。比如说,下载了 45% 之后,网络断开了;但 ProgressBar 一直显示 45%。

一旦发生这种情况,是否会引发任何属性/事件?请帮忙。附上我的代码供您参考。谢谢。

private void CheckForUpdate_Load(object sender, EventArgs e)
{
    string downloadURL = Convert.ToString(ConfigurationManager.AppSettings["TempDownloadURL"]);

    WebClient wcDownloadFile = new WebClient();
    Uri myUri = new Uri(downloadURL);

    wcDownloadFile.DownloadFileAsync(myUri, downloadLocation);
    wcDownloadFile.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wcDownloadFile_DownloadProgressChanged);
}

void wcDownloadFile_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
    try
    {
        int bytesDownloaded = Int32.Parse(e.BytesReceived.ToString());
        int totalBytes = Int32.Parse(e.TotalBytesToReceive.ToString());

        progBarSoftPhone.Value = e.ProgressPercentage;
        lblStatus.Text = (bytesDownloaded / 1024).ToString() + " KB out of " + (totalBytes / 1024).ToString() + " KB downloaded (" + e.ProgressPercentage.ToString() + "%).";
    }
    catch (Exception ex)
    {
        MessageBox.Show("ERROR: " + ex.Message, "ERROR", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

【问题讨论】:

  • 让计时器每隔一分钟检查一次连接怎么样。真的有那么糟糕吗?
  • @Rapsalands - 计时器确实有帮助。但是,实际上我不建议在万不得已之前使用 Timers。

标签: c# windows progress


【解决方案1】:
  1. 您可以利用 NetworkChange.NetworkAvailabilityChanged 事件 http://msdn.microsoft.com/en-us/library/system.net.networkinformation.networkchange.networkavailabilitychanged.aspx 如果 LAN 出现问题,它会告诉您,例如:网线被拔掉或用户自己禁用了 NetworkInterface。

  2. 万一出现网络掉线,您需要对自己的服务器进行某种 ping 机制来检查服务器是否可访问,您可以在开始下载 ping 时启动 Timer 并定期检查直到下载完成,下载完成或用户取消后,您可以停止计时器。

【讨论】:

  • 谢谢@Sriram。这正是我一直在寻找的。 :-)
  • 是的@Sriram,使用“NetworkAvailabilityChanged”,我可以在我的互联网掉线时捕获事件。
【解决方案2】:

DownloadFileCompleted 事件添加事件监听器并检查AsyncCompletedEventArgs 的Error 属性。

在您的 CheckForUpdate_Load 方法中添加:

wcDownloadFile.DownloadFileCompleted += WebClOnDownloadFileCompleted;

然后在处理程序中,您可以在发生错误时停止进度条:

private void WebClOnDownloadFileCompleted(object sender, 
    AsyncCompletedEventArgs asyncCompletedEventArgs)
                    {
                       if (asyncCompletedEventArgs.Error != null)
                        // code to handle it
                    }

【讨论】:

  • 另见此答案以配置超时stackoverflow.com/a/3052637/860585
  • 感谢 Adrian 的回复,但您指的是哪个对象的 Error 属性?
  • @Adrian,感谢您的代码。问题是,万一互联网消失,“完成”事件不会被调用。我通过在下载过程中取出我的 LAN 电缆来检查这一点。
  • 查看 Rotem 提供的链接,了解如何指定超时。也看看这个问题:stackoverflow.com/questions/4745553/…
  • 感谢 Adrian 和 Rotem 的所有帮助。 :-) 问题已经解决了。
猜你喜欢
  • 1970-01-01
  • 2015-11-23
  • 1970-01-01
  • 2013-04-06
  • 2010-10-15
  • 2013-03-28
  • 2013-10-09
  • 2014-02-09
  • 2012-08-04
相关资源
最近更新 更多