【问题标题】:Ping does not work with BackgroundWorker [duplicate]Ping 不适用于 BackgroundWorker [重复]
【发布时间】:2016-01-31 00:34:19
【问题描述】:
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.";
    }
}

dowork 每 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 上的pingtxtButton 还是更一般的ContentControl
  • 然后抛出System.InvalidOperationException,对吧?

标签: c# wpf


【解决方案1】:

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

我测试过,这对我有用。

【讨论】:

  • 谢谢。调用它就可以了。
猜你喜欢
  • 2013-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-09
  • 2021-09-25
  • 1970-01-01
相关资源
最近更新 更多