如何以线程安全的方式访问 c# WPF 控件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1284017/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to access c# WPF control in thread safe way?
提问by Sebastian Gray
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 -
为此,我尝试使用 MSDN 中的示例,但它们似乎仅适用于 Windows 窗体。例如使用 .InvokeRequired 的方法依赖于 windows 窗体控件,但是此方法不适用于 WPF 控件。Backgound worker 方法InvalidOperationException
也会抛出一个-
The calling thread cannot access this object because a different thread owns it.
调用线程无法访问此对象,因为其他线程拥有它。
So how can this be done in the context of WPF?
那么如何在 WPF 的上下文中做到这一点呢?
采纳答案by Noldorin
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.
您只想使用该Dispatcher.Invoke
方法(或异步等效项Dispatcher.BeginInvoke
),它将对主 WPF UI 线程的调用进行封送处理。
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.
本DependencyObject
类包含一个Dispatcher
属性,这意味着它从该类继承也提供这种特性,在类似的WinForms方式所有控件和其他对象。此外,该Application
对象提供对调度程序的访问。
An example usage might be the following (in code-behind of a Window
/UserControl
):
一个例子的使用可能是以下(在代码隐藏一个的Window
/ UserControl
):
this.Dispatcher.Invoke((Action)(() =>
{
...
}));