使用 .NET Framework 2.0 显示 Internet 连接状态图标






4.74/5 (11投票s)
2005 年 7 月 20 日
2分钟阅读

71954

1994
本文解释了如何使用 BackgroundWorker 和 StatusStrip 在 StatusStrip 上显示 Internet 连接状态图标,使用 .NET Framework 2.0。
引言
越来越多的应用程序依赖于可用的 Internet 连接来执行业务层的操作,例如调用 Web 服务、获取数据等。通常,您希望知道当前环境是否真的已连接。有多种方法可以实现这一点,您可以使用 System.Net
命名空间检查每个 NetworkInterface
的状态,但即使具有以太网连接或类似连接,也不能真正告诉您是否有可用的 Internet 连接。
本文展示了一种在 StatusStrip
上获取简单图标的方法,该图标显示计算机是否已连接到 Internet。
使用代码
基本上,您希望使用 Timer
来执行 HTTP-GET,以查看特定网站是否可用。
此类功能的唯一要求是,我们不想停止当前的 UI 线程。因此,我使用 BackgroundWorker
对象来执行查询。BackgroundWorker
对象声明了 DoWork
方法,该方法定义了一个自定义事件处理程序,该处理程序定义了 DoWorkEventArgs
类,您可以在其中将实际结果传递回 UI 线程。非常重要的是,您不要尝试在此方法中与任何 UI 元素交互,因为这正在单独的线程上运行。
private void InitializeComponent()
{
// Background Worker
this._worker = new BackgroundWorker();
this._worker.WorkerReportsProgress = false;
this._worker.WorkerSupportsCancellation = false;
this._worker.DoWork += new
DoWorkEventHandler(this.BackgroundWorker_DoWork);
this._worker.RunWorkerCompleted += new
RunWorkerCompletedEventHandler(this.BackgroundWorker_RunWorkerCompleted);
// Timer
this._updateTimer = new Timer();
this._updateTimer.Enabled = !this.DesignMode;
// Enabled when not in design mode
this._updateTimer.Tick += delegate { this.OnTick(); };
}
private void OnTick()
{
if (this.DesignMode)
return;
// Stop the timer while the process is running
this._updateTimer.Enabled = false;
// Disable so we get the grayed-out look
this.Enabled = false;
this.Invalidate();
// Execute the Ping Query on a separate thread...
this._worker.RunWorkerAsync();
}
查询非常简单,我针对一个应该“始终”可用的 URL 执行一个简单的 HttpWebRequest
,例如您的公司网站,http://www.microsoft.com 或 http://www.google.com。归根结底,这是实际了解您是否有可用 Internet 连接的唯一方法。
private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
try
{
// Create an HTTP Web request
// to an Uri that's always available.
HttpWebRequest request = (HttpWebRequest)
HttpWebRequest.Create(this._alwaysAvailableUrl);
// Perform GET
HttpWebResponse response =
(HttpWebResponse) request.GetResponse();
if (HttpStatusCode.OK == response.StatusCode)
{
// HTTP = 200, close the request and return true
response.Close();
e.Result = true;
}
else
{
// Other status; return false
e.Result = false;
}
}
catch (WebException)
{
// Deffinitely offline
e.Result = false;
}
}
在 BackgroundWorker
对象完成其工作(在 DoWork
事件中定义)后,它会调用 RunWorkerCompleted
事件,该事件也定义了一个自定义事件处理程序,该处理程序声明了 RunWorkerCompletedEventArgs
类。通过此类,我们将管理 ToolStripStatusLabel
的呈现方式。
private void BackgroundWorker_RunWorkerCompleted(object
sender, RunWorkerCompletedEventArgs e)
{
if (null != e.Error)
{
// Throw the error to the User Interface...
// This shouldn't really get to happen.
Trace.TraceError(e.Error.Message);
throw e.Error;
}
else
{
if ((bool) e.Result) // Online
{
this.Image = Properties.Resources.Online;
this.Text = Properties.Resources.MainFormConnectionStatusOnline;
}
else // Offline
{
this.Image = Properties.Resources.Offline;
this.Text = Properties.Resources.MainFormConnectionStatusOffline;
}
// Redraw
this.Invalidate();
}
// Re-enable and restart timer...
this.Enabled = true;
this._updateTimer.Enabled = true;
}
结论
.NET Framework 2.0 使得使用后台线程变得非常容易,为您的 UI 提供了流畅而有用的体验。现在,如果您使用的是 Visual Studio .NET 2005 的 April CTP,我强烈建议您手动为 DoWork
事件分配您的委托,因为 VS.NET 中存在一个错误,当它试图重写不使用 UI 代码的注释时,它可以从单独的线程中替换您的实际代码。
如果您需要 Internet 连接才能使用 Web 服务,您可能还需要考虑在您的 Web 服务中添加一个 GetVersion
Web 方法,并尝试访问此服务,因为毕竟,如果您的 Web 服务器已关闭,则拥有可用的连接没有任何意义。
历史
- 演示版本 - 1.0.0.0 - 附在本文中。