Getting the right WPF dispatcher in a thread [duplicate]

試著忘記壹切 提交于 2019-12-07 03:28:58

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!