C# Ping不与BackgroundWorker一起工作
dowork每3秒运行一次 MainWindow.GlobalVar.global_ip是一个字符串,始终为“127.0.0.1” 及 未在上下文中设置pingtxt。有什么问题吗C# Ping不与BackgroundWorker一起工作,c#,wpf,C#,Wpf,dowork每3秒运行一次 MainWindow.GlobalVar.global_ip是一个字符串,始终为“127.0.0.1” 及 未在上下文中设置pingtxt。有什么问题吗 pingtxt详细信息 您只能从UI线程修改UI 使用: 我进行了测试,这对我很有效。是pingtxt一个按钮,或者更一般地说是UI上的内容控件,并抛出一个系统。InvalidOperationException,对吗?thx。调用它工作。 private void backworker_PING_DoWork(
pingtxt详细信息
您只能从UI线程修改UI 使用:
我进行了测试,这对我很有效。是
pingtxt
一个按钮
,或者更一般地说是UI上的内容控件
,并抛出一个系统。InvalidOperationException
,对吗?thx。调用它工作。
private void backworker_PING_DoWork(object sender, DoWorkEventArgs e)
{
bool pingable = false;
Ping pinger = new Ping();
try
{
PingReply reply = pinger.Send(MainWindow.GlobalVar.global_ip);
if (reply.Status == IPStatus.Success)
{
pingable = true;
}
else
{
pingable = false;
}
}
catch (PingException)
{
// Discard PingExceptions and return false;
}
//System.Windows.Forms.MessageBox.Show("...");
if (pingable == true)
{
this.pingtxt.Content = MainWindow.GlobalVar.global_ip + " is Ping able.";
}
else
{
this.pingtxt.Content = @"[!]" + MainWindow.GlobalVar.global_ip + " is unPingable.";
}
}
<Label x:Name="pingtxt" Content="***?" HorizontalAlignment="Left" Margin="650,139,0,0" VerticalAlignment="Top" Height="26" RenderTransformOrigin="0.5,0.5">
<Label.Foreground>
<LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
<GradientStop Color="White" Offset="0"/>
<GradientStop Color="#FF8F8F8F" Offset="1"/>
</LinearGradientBrush>
</Label.Foreground>
<Label.Effect>
<DropShadowEffect ShadowDepth="0" BlurRadius="2" Opacity="0.5"/>
</Label.Effect>
</Label>
private void backworker_PING_DoWork(object sender, DoWorkEventArgs e)
{
bool pingable = false;
Ping pinger = new Ping();
try
{
PingReply reply = pinger.Send(MainWindow.GlobalVar.global_ip);
if (reply.Status == IPStatus.Success)
{
pingable = true;
}
else
{
pingable = false;
}
}
catch (PingException)
{
// Discard PingExceptions and return false;
}
//System.Windows.Forms.MessageBox.Show("...");
if (pingable == true)
{
System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() => { pingtxt.Content = MainWindow.GlobalVar.global_ip + " is Ping able."; }));
}
else
{
System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() => { pingtxt.Content = MainWindow.GlobalVar.global_ip + " is unPingable."; }));
}
}