This question already has answers here:
How do I update a Label from within a BackgroundWorker thread?
                                
                                    (4个答案)
                                
                        
                                3年前关闭。
            
                    
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详细信息

最佳答案

您只能从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."; }));
    }
}


我测试了,这对我有用。

08-26 15:00