开发者

Getting the right WPF dispatcher in a thread [duplicate]

This question already has answers here: How do I get the UI thread's Dispatcher? (2 answers) Closed 7 years ago. 开发者_高级运维

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


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.


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.


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜