Getting the right WPF dispatcher in a thread

22,566

Solution 1

You most likely can just use Dispatcher.CurrentDispatcher.Invoke...

However, if for some reason that doesn't work, you could have your class receive a reference to the Dispatcher as part of its constructor. Just pass in Dispatcher.CurrentDispatcher from the UI thread at construction time.

Solution 2

As explained in this answer:

You can grab the UI Dispatcher from the static application instance: Application.Current.Dispatcher

You may want to check Application.Current for null first, as it can be cleared during a shutdown sequence.

Also, here are the docs for the Application class.

Solution 3

Most WPF controls derive from DispatcherObject which has the Dispatcher property you need. So basically you would use the dispatcher from the control you want to use. In this case, for example, the Window where the MediaElement is added to.

Share:
22,566
Admin
Author by

Admin

Updated on July 18, 2022

Comments

  • Admin
    Admin almost 2 years

    In the constructor of an object i need to create a WPF mediaElement object:

    m_videoMedia = new MediaElement();
    

    but the class can also be instantiated from a other thread so i need to use

    Dispatcher.Invoke(DispatcherPriority.Normal,
        (Action)(() => { m_videoMedia = new MediaElement(); })); 
    

    But how can I get the right dispatcher instance in that constructor :s