How do I get the UI thread's Dispatcher?

WpfMultithreadingDispatcher

Wpf Problem Overview


Is there any way to get the UI thread's Dispatcher when you have no reference to any UI elements?

Wpf Solutions


Solution 1 - Wpf

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.

Solution 2 - Wpf

The following works much better for me when being used in a WinForms application that happens to be also using WPF (in my case Esri's Arcmap.exe)

private System.Windows.Threading.Dispatcher Dispatcher { get; set; }

// I put this in my view model constructor as it MUST be called from UI thread
Dispatcher = System.Windows.Threading.Dispatcher.CurrentDispatcher;

The other method (which involved calling new System.Windows.Application() to populate System.Windows.Application.Current) caused issues for me every time I opened a new WPF window and then closed it. Not only did this null out System.Windows.Application.Current, but I could no longer open up new windows as their InitializeComponents() methods, all failed with:

> System.InvalidOperationException: 'The Application object is being > shut down.'

So far the new solution is working without those side effects.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPeterView Question on Stackoverflow
Solution 1 - WpfAbe HeidebrechtView Answer on Stackoverflow
Solution 2 - WpfM TownsendView Answer on Stackoverflow