我在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/