如何以线程安全的方式访问c# WPF控件?
我已经尝试使用 MSDN 中的示例来实现此目的,但它们似乎仅适用于 Windows 窗体。 例如,使用 .InvokeRequired 的方法依赖于 Windows 窗体控件,但此方法不适用于 WPF 控件。 Backgound 工作方法也会抛出 InvalidOperationException
-
调用线程无法访问此 对象,因为不同的线程拥有 它。
那么在 WPF 上下文中如何做到这一点呢?
I've tried using the examples from MSDN for this but they seem to only be applicable to Windows Forms. For instance the method of using .InvokeRequired relies on the windows forms control, however this method isn't available for WPF controls. The Backgound worker method throws an InvalidOperationException
as well -
The calling thread cannot access this
object because a different thread owns
it.
So how can this be done in the context of WPF?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您只想使用
调度程序。 Invoke
方法(或异步等效的Dispatcher.BeginInvoke
),该方法会将调用编组到主 WPF UI 线程。DependencyObject
类包含Dispatcher
属性,这意味着从该类继承的所有控件和其他对象也提供该属性,其方式类似于 WinForms。 此外,Application
对象提供对调度程序的访问。示例用法可能如下(在
Window
/UserControl
的代码隐藏中):You simply want to use the
Dispatcher.Invoke
method (or the asynchronous equivalentDispatcher.BeginInvoke
), which will marshal the call to the main WPF UI thread.The
DependencyObject
class contains aDispatcher
property, which means all controls and other objects which inherit from this class also provide this property, in a way similar to WinForms. In addition, theApplication
object provides access to the dispatcher.An example usage might be the following (in code-behind of a
Window
/UserControl
):