如何访问线程安全的方式C#WPF控件? [英] How to access c# WPF control in thread safe way?

查看:327
本文介绍了如何访问线程安全的方式C#WPF控件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直使用从MSDN示例此尝试,但他们似乎只适用于Windows窗体。例如使用.InvokeRequired的方法依赖于Windows窗体控件,但是这种方法并不适用于WPF控件。该Backgound辅助方法抛出出现InvalidOperationException ,以及 -

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.

因此​​,如何能在这个WPF的情况下怎么办?

So how can this be done in the context of WPF?

推荐答案

您只是想使用<$c$c>Dispatcher.Invoke方法(或异步相当于 Dispatcher.BeginInvoke ),这将封送调用主WPF UI线程。

You simply want to use the Dispatcher.Invoke method (or the asynchronous equivalent Dispatcher.BeginInvoke), which will marshal the call to the main WPF UI thread.

的DependencyObject 类包含一个<一个href=\"http://msdn.microsoft.com/en-us/library/system.windows.dependencyobject.dispatcher%28VS.95%29.aspx\"><$c$c>Dispatcher属性,这意味着它从该类继承也提供了这个属性,在类似的WinForms方式所有控件和其他对象。此外,应用对象提供接入调度。

The DependencyObject class contains a Dispatcher 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, the Application object provides access to the dispatcher.

使用示例可能是以下(在code-后面的窗口 / 用户控件

An example usage might be the following (in code-behind of a Window/UserControl):

this.Dispatcher.Invoke((Action)(() =>
    {
        ...
    }));

这篇关于如何访问线程安全的方式C#WPF控件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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