Dispatcher.CurrentDispatcher 与 Application.Current.Dispatcher [英] Dispatcher.CurrentDispatcher vs. Application.Current.Dispatcher
问题描述
Dispatcher.CurrentDispatcher
(System.Windows.Threading
)和Application.Current.Dispatcher
(>System.Windows
)?
我的直觉告诉我 Application.Current.Dispatcher
永远不会改变并且对当前应用程序中的所有线程都是全局的,而 Dispatcher.CurrentDispatcher
可能会创建一个新实例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.
正确吗?
如果是,Dispatcher.CurrentDispatcher
的目的是否主要用于多线程 UI?
If it is, is the purpose of Dispatcher.CurrentDispatcher
primarily for multi-threaded UI?
推荐答案
我的直觉告诉我 Application.Current.Dispatcher 永远不会改变并且对当前应用程序中的所有线程是全局的,而Dispatcher.CurrentDispatcher 可能会创建一个新的 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.
没错.
此外,从非 UI 线程访问 Dispatcher.CurrentDispatcher
没有任何意义.除非您调用 Dispatcher,否则它什么都不做.Run
,进入无限消息循环并不是您想要在工作线程中执行的操作.
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.
所以:
在最常见的场景中,您的应用只有一个 UI 线程,
Application.Current.Dispatcher
和Dispatcher.CurrentDispatcher 将返回相同的实例.您使用哪一个只是一个偏好问题.
In the most common scenario, where your app only has a single UI thread,
Application.Current.Dispatcher
andDispatcher.CurrentDispatcher
from within the UI thread will return the same instance. Which one you use is simply a matter of preference.
如果您的应用有多个 UI 线程,那么每个 DispatcherObject
将是与在构建时创建的 UI 线程的调度程序永久关联.在这种情况下,Application.Current.Dispatcher
将引用您的应用程序生成的线程的调度程序;您将无法使用它向其他 UI 线程拥有的控件发布消息.
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.
这篇关于Dispatcher.CurrentDispatcher 与 Application.Current.Dispatcher的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!