How to access c# WPF control in thread safe way?

后端 未结 1 1692
庸人自扰
庸人自扰 2020-12-02 21:30

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 window

相关标签:
1条回答
  • 2020-12-02 21:58

    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)(() =>
        {
            ...
        }));
    
    0 讨论(0)
提交回复
热议问题