How can I get the UI manager thread?

Is there a way to get a Dispatcher UI thread if you don't have a link to any UI elements?

+49
multithreading wpf dispatcher
Apr 18 2018-10-18T00:
source share
3 answers

You can grab the UI manager from an instance of a static application: Application.Current.Dispatcher

You can first check Application.Current for null since it can be cleared during the shutdown sequence.

+92
Apr 19 '10 at 21:54
source share

The following works much better for me when used in a WinForms application that also uses WPF (in my case Esri 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; 

Another method (which included calling new System.Windows.Application() to populate System.Windows.Application.Current ) caused problems for me every time I opened a new WPF window and then closed it. This not only excluded System.Windows.Application.Current , but I could no longer open new windows, as their InitializeComponents() methods did not work with:

System.InvalidOperationException: 'Application object is closing.'

So far, the new solution has worked without these side effects.

+2
Dec 10 '18 at
source share

Calling the Dispatcher.CurrentDispatcher property will get the current instance of the Dispatcher stream or create a new one for the stream if it does not exist.

 using System.Windows.Threading; Dispatcher dispatcher = Dispatcher.CurrentDispatcher; 

This may be undesirable if you do not want to accidentally create unnecessary instances of Dispatcher .

Instead, you can use the Dispatcher.FromThread(Thread) method.

 using System.Windows.Threading; Dispatcher dispatcher = Dispatcher.FromThread(System.Threading.Thread.CurrentThread); 

This method will get a Dispatcher instance from the specified stream. If the Dispatcher instance does not exist for the specified stream, it will return null .

0
Jul 09 '19 at 8:20
source share



All Articles