How to access c# WPF control in thread safe way?
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.
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.
An example usage might be the following (in code-behind of a Window
/UserControl
):
this.Dispatcher.Invoke((Action)(() =>
{
...
}));
Sebastian Gray
Updated on August 17, 2020Comments
-
Sebastian Gray over 3 years
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?
-
Sebastian Gray over 14 yearsThanks, that worked perfectly. It actually looks a lot simpler in WPF than win forms, when you know what you need to do ;-)
-
Noldorin over 14 yearsNo problem. And yeah WPF certainly does have a better threading/message pump model.