WPF跨线程对象访问 [英] WPF Cross Thread Object Access

查看:527
本文介绍了WPF跨线程对象访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个问题关于WPF中跨线程调用。

I have an issue regarding cross thread calls in 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));
            }
        }

当我运行此code,它可以正确处理第一次迭代。然而,第二次迭代中的行:

When I run this code, it works correctly for the first iteration. However during the second iteration the line:

  r.Dispatcher.Invoke(new ThreadStart(() => status= ((StatusButtonProperties)r.Tag).StatusInformation))

导致此异常:

Cannot use a DependencyObject that belongs to a different thread than its parent Freezable.

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

I've tried a few solutions but I can't find anything workable.

任何帮助AP preciated!

Any help appreciated!

推荐答案

我想改写这个为:

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;
    }

}));

这篇关于WPF跨线程对象访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆