7

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

Lars Truijens
  • 42,837
  • 6
  • 126
  • 143
Bert
  • 71
  • 1
  • 1
  • 2

4 Answers4

10

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.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • 8
    According to msdn this will return the dispatcher associated with the current thread and will create a new one of one is not already created. This does not sound like something you want to do in this case. You would need the dispatcher associated with the UI. Or more specifically the dispatcher of a specific Window. – Lars Truijens Mar 17 '10 at 20:44
  • +1 for passing a reference to the current dispatcher. – Nate Mar 18 '10 at 14:34
  • The static Dispatcher.CurrentDispatcher did not work for me in a similar scenario. I tried Application.Current.Dispatcher as suggested by sinelaw - that worked. – Jørn Wildt Dec 29 '13 at 19:38
6

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.

Community
  • 1
  • 1
sinelaw
  • 16,205
  • 3
  • 49
  • 80
  • Checking whether `Application.Current` is null is somehow risky. It can be valid when you check it (with `if`) in working thread, but can become null when using it afterwards. I usually put `Application.Current.Dispatcher.Invoke` in try-catch block. – guan boshen Jul 08 '18 at 14:09
2

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.

Lars Truijens
  • 42,837
  • 6
  • 126
  • 143
-2

If you add references to System.Windows.Forms to your project, you can continue use Application.DoEvents() in WPF.

bfavaretto
  • 71,580
  • 16
  • 111
  • 150