简体   繁体   中英

How to get dispatcher anywhere in WPF application

I want to get current dispatcher in WPF application. The code where I want to get the dispatcher is in the .cs class file(regular C# class). Application.Current.Dispatcher.Invoke() and other ....Current.Dispatcher.Invoke() are not available.

Is there any way to do so?

why the class Application.Current.Dispatcher is not available? Have you referenced to the PresentationFramework assembly yet?

您可以从窗口或当前窗口获取分派器。

Application.Current.MainWindow.Dispatcher.Invoke() 

I think System.Windows.Threading.Dispatcher.CurrentDispatcher should do the job, but you should be aware that the Dispatcher you will receive depends on the thread you are calling this method from. Here you can see very good explanation what's the exact difference between the two - Dispatcher.CurrentDispatcher vs. Application.Current.Dispatcher .

My gut tells me that Application.Current.Dispatcher will never change and is global to all threads in the current application, while Dispatcher.CurrentDispatcher may create a new instance of Dispatcher depending on the thread from which it was called.

That's why I would advise you to find a way to abstract Application.Current.Dispatcher or the Dispatcher of some view and to access it through this abstraction - it is just safer for multithreading scenarios.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM