What are the differences between Dispatcher.CurrentDispatcher
(in System.Windows.Threading
) and Application.Current.Dispatcher
(in System.Windows
)?
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.
Is that correct?
If it is, is the purpose of Dispatcher.CurrentDispatcher
primarily for multi-threaded UI?
Current. Dispatcher is an instance property of the application which is assigned upon construction to be the dispatcher of the current thread. And as the documentation of Dispatcher.
BeginInvoke(DispatcherPriority, Delegate) Executes the specified delegate asynchronously at the specified priority on the thread the Dispatcher is associated with. BeginInvoke(Delegate, DispatcherPriority, Object[])
The UI thread queues work items inside an object called a Dispatcher. The Dispatcher selects work items on a priority basis and runs each one to completion. Every UI thread must have at least one Dispatcher, and each Dispatcher can execute work items in exactly one thread.
WPF Dispatcher is associated with the UI thread. The UI thread queues methods call inside the Dispatcher object. Whenever your changes the screen or any event executes, or call a method in the code-behind all this happen in the UI thread and UI thread queue the called method into the Dispatcher queue.
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 is correct.
Additionally, there is no point whatsoever in accessing Dispatcher.CurrentDispatcher
from a non-UI thread. It will do nothing unless you call Dispatcher.Run
, and going into an infinite message loop is not what you want to be doing from within worker threads.
So:
In the most common scenario, where your app only has a single UI thread, Application.Current.Dispatcher
and Dispatcher.CurrentDispatcher
from within the UI thread will return the same instance. Which one you use is simply a matter of preference.
If your app has more than one UI thread then each DispatcherObject
will be permanently associated with the dispatcher of the UI thread it was created in upon construction. In this case, Application.Current.Dispatcher
will refer to the dispatcher of the thread your application spawned with; you will not be able to use it to post messages to controls owned by your other UI threads.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With