调度器。电流调度器与应用程序。电流。调度器

Dispatcher.CurrentDispatcher(在 System.Windows.Threading)和 Application.Current.Dispatcher(在 System.Windows)有什么不同?

我的直觉告诉我,Application.Current.Dispatcher永远不会改变,它对当前应用程序中的所有线程都是全局的,而 Dispatcher.CurrentDispatcher可能会根据调用它的线程创建一个新的 Dispatcher实例。

是这样吗?

如果是的话,Dispatcher.CurrentDispatcher主要用于多线程 UI 吗?

62488 次浏览

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, the Application.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.CurrentDispatcher points out:

Gets the Dispatcher for the thread currently executing and creates a new Dispatcher if one is not already associated with the thread.


If it is, is the purpose of Dispatcher.CurrentDispatcher primarily for multi-threaded UI?

Possibly, i have not encountered any use in getting the dispatcher of a background thread as you usually have no UI-elments belonging to them to which you may want to dispatch operations.

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.

To put it simply...

Dispatcher.CurrentDispatcher gets the dispatcher for the current thread. So, if you're looking for the UI thread's Dispatcher from a background process, don't use this.

Application.Current.Dispatcher will always give you the UI thread's dispatcher, as this is the thread that spins up the sole Application instance.