我尝试实现(在WPF、C#中)Ellipse
控件,该控件根据与google.com的连接改变其颜色。 。如果与Google有连接,则椭圆为绿色;否则它是红色的。
我这样编码:
XAML 代码
<Window.Resources>
<l:InternetConnectionToBrushConverter x:Key="InternetConnectionConverter" />
</Window.Resources>
<Grid>
<DockPanel LastChildFill="True">
<StatusBar Height="23" Name="statusBar1" VerticalAlignment="Bottom" DockPanel.Dock="Bottom">
<Label Content="Google connection:" Name="label1" FontSize="10" Padding="3" />
<Ellipse Name="ellipse1" Stroke="Black" Width="10" Height="10" Fill="{Binding Converter={StaticResource InternetConnectionConverter}}" Margin="0,4,0,0" />
</StatusBar>
</DockPanel>
</Grid>
和C#后台代码(值转换器和函数检查连接):
public class InternetConnectionToBrushConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (targetType != typeof(Brush))
throw new InvalidOperationException("The target must be a Brush!");
return CheckConnection("http://www.google.com/") == true ? Brushes.Green : Brushes.Red;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
/// <summary>
/// Checks connection to specified URL.
/// </summary>
/// <param name="URL"></param>
/// <returns><b>True</b> if there is connection. Else <b>false</b>.</returns>
private bool CheckConnection(String URL)
{
try
{
HttpWebRequest request = WebRequest.Create(URL) as HttpWebRequest;
request.Timeout = 15000;
request.Credentials = CredentialCache.DefaultNetworkCredentials;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
return response.StatusCode == HttpStatusCode.OK ? true : false;
}
catch (Exception e)
{
Debug.WriteLine(e.ToString());
return false;
}
}
}
它运行良好,但有两个问题:
- 检查连接需要一些时间,所以我认为我应该在新线程中执行此操作(如果我错了,请告诉我原因)
- 更重要的是 - 它检查与 Google 的连接仅一次,当程序开始运行时(尽管我使用绑定(bind),所以我希望会有持续的连接监控)
我该如何解决这个问题?
我想要持续监控连接,这样当我断开互联网连接时,Ellipse
控件就会改变其颜色。
最佳答案
您必须稍微改变一下您的架构。
您不能在 IValueConverter
中使用线程来避免锁定 UI。在从 IValueConverter
返回之前,您仍然需要等待线程完成。
您需要创建一个 HasConnection
属性来绑定(bind)椭圆颜色。然后您可以在另一个线程中运行连接检查。最好使用BackgroundWorker
。检查完成后,应更新 HasConnection
属性。然后,您可以使用计时器定期检查连接,并在每次检查后更新 HasConnection
。
编辑
您还可以监控NetworkChange.NetworkAvailabilityChanged
事件来查明本地网络连接何时启动或关闭。但是,如果您想确保实际上可以连接到目标,则应该保留旧的 CheckConnection
,但在启动时、网络可用性发生变化时以及定期在网络上发生变化时调用 CheckConnection
。计时器。
关于c# - 监控互联网连接状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12238444/