.NET数据绑定的跨线程问题 [英] Cross-thread problems with .NET data binding

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

问题描述

我有许多Windows窗体控件,这些控件用于与程序对象进行交互。当前,他们订阅对象上的更新事件,并在需要时手动更新值。我想使用数据绑定替换所有(或尽可能多的)样板代码。

I have a number of Windows Forms controls which are used to interact with my program objects. Currently they subscribe to an "Updated" event on the object and manually update values when needed. I would like to replace all (or as much as possible) of this boilerplate code using data binding.

我遇到的问题是对象状态可以是随时可以通过多个不同线程中的任何一个进行修改。当前,我使用Invoke()处理此问题,效果很好,但是当我切换到数据绑定时,我会被非法的跨线程控制异常所淹没。是否有一种首选的方法可以使用数据绑定来优雅地处理此问题,还是我最好还是按照现在的样子来处理?

The problem I'm running into is that the object state can be modified by any one of several different threads at any moment. Currently I use Invoke() to handle this, which works fine, but when I switch to data binding I get swamped by illegal cross-thread control exceptions. Is there a preferred method to handle this gracefully using data binding, or am I better off just leaving things the way they are now?

谢谢!

推荐答案

如果要将数据绑定到从基础线程更新的数据源,则必须移动执行以下操作的代码:通过调用 <$ c来更新到UI线程$ c>调用

If you are data binding your controls to the data sources that are being updated from the underlying thread, then you will have to move the code that does the updating to the UI thread through a call to Invoke.

或者,如果您愿意,您可以获得 ISynchronizeInvoke 实现(或 SynchronizationContext ),并在U上触发所有事件我穿线。当然,这可能会导致代码意外问题,因为您首先没有在UI线程上触发事件。

Or, if you want, you could get a ISynchronizeInvoke implementation (or a SynchronizationContext) and have all the events fire on the UI thread. Of course, this could cause unintended problems with your code, as you weren't firing the events on the UI thread in the first place.

这篇关于.NET数据绑定的跨线程问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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