使用 Dispatcher 更改标签的前景会抛出异常

Using Dispatcher to change a label's foreground throws an exception

我正在尝试制作一个 CPU 友好的无限循环,它将每 2 秒更新一次标签。

在更新标签时,我可以使用 Dispatcher 来更改其 ContentToolTip 值,但我无法更改其 Foreground一些原因。

InvalidOperationException: can not use a DependencyObject that belongs to another thread than its Freezable parent.

有我的代码:

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();

(是的,我知道这不是一个 CPU 友好的循环,我这样做是为了测试目的)。

感谢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() returns 类似于 return (SolidColorBrush)new BrushConverter().ConvertFromString("#b71c1c");