c# - WPF跨线程对象访问

标签 c# .net wpf multithreading

我在WPF中有关于跨线程调用的问题。

            foreach (RadioButton r in StatusButtonList)
        {
            StatusType status = null;
            r.Dispatcher.Invoke(new ThreadStart(() => status= ((StatusButtonProperties)r.Tag).StatusInformation));
            if (AppLogic.CurrentStatus == null || AppLogic.CurrentStatus.IsStatusNextLogical(status.Code))
            {
                SolidColorBrush green = new SolidColorBrush(Color.FromRgb(102, 255, 102));
                r.Dispatcher.Invoke(new ThreadStart(() =>  r.Background = green));
            }
            else
            {
                SolidColorBrush red = new SolidColorBrush(Color.FromRgb(255, 0, 0));
                r.Dispatcher.Invoke(new ThreadStart(() => r.Background = red));
            }
        }

当我运行此代码时,它可以在第一次迭代中正常工作。但是,在第二次迭代中,该行:
  r.Dispatcher.Invoke(new ThreadStart(() => status= ((StatusButtonProperties)r.Tag).StatusInformation))

导致此异常:
Cannot use a DependencyObject that belongs to a different thread than its parent Freezable.

我尝试了一些解决方案,但找不到任何可行的方法。

任何帮助表示赞赏!

最佳答案

我将其重写为:

r.Dispatcher.Invoke(new Action(delegate()
{
    status = ((StatusButtonProperties)r.Tag).StatusInformation;

    if (AppLogic.CurrentStatus == null || AppLogic.CurrentStatus.IsStatusNextLogical(status.Code))
    {
        r.Background = Brushes.Green;
    }
    else
    {
        r.Background = Brushes.Red;
    }

}));

关于c# - WPF跨线程对象访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5868451/

相关文章:

c# - Rotativa - 奇怪的 header 输出

c# - 验证 SaveFileDialog 的 InitialDirectory?

c# - 获取数组的尾部

c# - 使用 C# 在字符串中查找具有频率的子字符串的最佳方法是什么?

javascript - 如何在 javascript 的 eval 函数中添加单引号?

wpf - 如何使用嵌套文本更改 WPF TabItem 的文本前景?

.net - 自动更新 .NET 应用程序

.net - 使用 LoadControl(Type, Object()) 以编程方式加载用户控件

使用两个任意点之间的 ArcSegment 计算半圆的 WPF 数学

wpf - 如何在 WPF 中的异步操作期间阻止 UI