代码之家  ›  专栏  ›  技术社区  ›  Enzo Innocenzi

使用Dispatcher更改标签的前景会引发异常

  •  0
  • Enzo Innocenzi  · 技术社区  · 7 年前

    Dispatcher 更改其 Content ToolTip 价值观,但我不能改变它 Foreground

    无效操作异常 :

    这是我的代码:

    private void SetPing(Brush foreground, string content, string tooltip)
    {
        try
        {
            this.Dispatcher.BeginInvoke(DispatcherPriority.Send, (Action)(() =>
            {
                this.Ping.Content = content;
                this.Ping.ToolTip = tooltip;
            }));
    
            // this.Dispatcher or this.Ping.Dispatcher throws the same error
            this.Ping.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)(() =>
            {
                this.Ping.Foreground = foreground;
            }));
        }
        catch (Exception)
        {
        }
    }
    

    我从 PerformPing 此处的方法:

    new Thread(() =>
    {
        while (true)
        {
            this.PerformPing(this.Host);
            Thread.Sleep(1);
        }
    }).Start();
    

    1 回复  |  直到 7 年前
        1
  •  0
  •   Enzo Innocenzi    7 年前

    幸亏 Peter Duniho 在回答问题时,我发现笔刷对象是在背景线程中创建的,这就是导致问题的原因。在中创建笔刷 Dispatcher

    private void SetPing(long ping, string content, string tooltip)
    {
        try
        {
            this.Dispatcher.BeginInvoke(DispatcherPriority.Send, (Action)(() =>
            {
                this.Ping.Content = content;
                this.Ping.ToolTip = tooltip;
                this.SetDock();
            }));
    
            if (this.EnableColors)
            {
                this.Ping.Dispatcher.BeginInvoke(DispatcherPriority.Send, (Action)(() =>
                {
                    this.Ping.Foreground = this.GetColorByPing(ping);
                }));
            }
        }
        catch (Exception ex)
        {
        }
    }
    

    哪里 GetColorByPing() 返回如下内容 return (SolidColorBrush)new BrushConverter().ConvertFromString("#b71c1c");