【问题标题】:Using Dispatcher to change a label's foreground throws an exception使用 Dispatcher 更改标签的前景会引发异常
【发布时间】:2017-08-20 13:56:28
【问题描述】:

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

在更新标签时,我可以使用Dispatcher 来更改它的Content 和ToolTip 值,但由于某种原因我不能更改它的Foreground。

无效操作异常: 不能使用属于另一个线程而不是其 Freezable 父线程的 DependencyObject。

这是我的代码:

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 友好的循环,我这样做是为了测试)。

【问题讨论】:

  • 如果没有可靠地重现问题的良好minimal reproducible example,就无法确定问题所在。但是根据您共享的一小部分代码,我猜您正在后台线程中创建 Brush 对象。这通常是不允许的。创建它后,您可以通过在Brush 上调用Freeze() 来使其工作。但坦率地说,如果你学会了编写 WPF 程序的正确方法,包括使用带有样式的 MVVM/数据绑定,那就更好了。那么你根本不需要BeginInvoke()。 (而且,使用Thread.Sleep(1) 不是 “CPU 友好”。)
  • 整个代码并没有添加那么多。 PerformPing 唯一要做的就是执行 ping 并调用 SetPing 并使用结果,其中 Brush 对象通过 BrushConverter 检索。那有帮助吗?我会试试Freeze()。另外,这是我为自己制作的一个非常小的程序。我不需要样式,也不需要数据绑定。此外,就像我说的(Yes, I know this is not a CPU-friendly loop, I made this for testing purposes). 但还是谢谢你。
  • “我在这个中不需要样式或数据绑定”——当然可以。仅仅因为它是“[你]为[你的]自己制作的一个非常小的程序”,这并不意味着这样做没有价值正确。
  • 你是对的。但是有更好的说法。我的意思是,机智。但无论如何,你帮助了我,谢谢。正如您指出的那样,即使有更好的方法可以在不使用Dispatcher 的情况下实现这一点,我也会以可接受的响应来回答这个帖子。

标签: c# multithreading dependency-properties dispatcher


【解决方案1】:

感谢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"); 的地方

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-23
    • 2021-08-24
    • 2015-03-20
    • 2014-11-05
    • 2023-03-14
    • 1970-01-01
    相关资源
    最近更新 更多