WPF 跨线程对象访问
我有一个关于 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.
我尝试了一些解决方案,但找不到任何可行的解决方案。
任何帮助表示赞赏!
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));
}
}
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))
Causes this exception:
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.
Any help appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我将其重写为:
I'd rewrite this to:
我假设您位于与创建这些单选按钮的线程不同的线程中。否则调用就没有意义。由于您是在该线程中创建 SolidColorBrush,因此那里已经存在潜在的跨线程调用。
让跨线程调用更加“厚重”会更有意义,即将 foreach 循环中的所有内容都放在单个 Invoke 调用中。
如果不同的调用不是相互依赖的,您还可以考虑使用
BeginInvoke
。I am assuming that you are in a different thread than the one which created those RadioButtons. Otherwise the invoking makes no sense. Since you are creating the SolidColorBrush in that thread, you already have a potential cross-thread call there.
It would make more sense to make the cross-thread calls more "chunky", i.e. put everything in the foreach loop in a single Invoke call.
You could also consider using
BeginInvoke
if the different calls are not interdependant.