tags:

views:

293

answers:

2

Hi,

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

+2  A: 

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
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
+1 for passing a reference to the current dispatcher.
Nate Bross
A: 

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