问题
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
回答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.
回答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.
回答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.
回答4:
If you add references to System.Windows.Forms
to your project, you can continue use Application.DoEvents()
in WPF.
来源:https://stackoverflow.com/questions/2465608/getting-the-right-wpf-dispatcher-in-a-thread