Ping不适用于BackgroundWorker

时间:2016-01-30 06:34:41

标签: c# wpf

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.";
    }
}
  

每3秒运行一次。

     

MainWindow.GlobalVar.global_ip是一个字符串,始终" 127.0.0.1"

     

     

pingtxt未设置上下文。问题是什么?

<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>
  

pingtxt详细信息

1 个答案:

答案 0 :(得分:3)

您只能从UI线程修改UI。

使用Dispatcher.Invoke

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."; }));
    }
}

我测试了,这对我有用。