问题描述
之间有什么 Dispatcher.CurrentDispatcher
的差异(在 System.Windows.Threading程序
)和 Application.Current.Dispatcher
(在 System.Windows
)?
我的直觉告诉我, Application.Current.Dispatcher
永远不会改变,是全球性的,以当前应用程序的所有线程,而 Dispatcher.CurrentDispatcher
可能产生的新实例调度
根据从它被称为线程。
这是否正确?
如果是,是 Dispatcher.CurrentDispatcher
的目的主要是为多线程的用户界面?
这是正确的。
此外,有任何从一个非UI线程访问 Dispatcher.CurrentDispatcher
没有任何意义。除非你把它叫做什么也不做<$c$c>Dispatcher.Run$c$c>,而进入无限的消息循环是不是你想要从工作线程在做什么。
所以:
-
在最常见的场景,在您的应用程序只有一个UI线程,
Application.Current.Dispatcher
和<$ C C> Dispatcher.CurrentDispatcher $从UI线程内将返回同一个实例。你用哪一个是简单的preference的问题。 -
如果您的应用程序有多个UI线程,则每<$c$c>DispatcherObject$c$c>会是它是在建设创造了UI线程的调度永久关联。在这种情况下,
Application.Current.Dispatcher
将指向您的应用程序产生了与线程的调度;你将不能够使用它来发布信息,以您的其他UI线程拥有的控制。
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?
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
andDispatcher.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.
这篇关于Dispatcher.CurrentDispatcher与Application.Current.Dispatcher的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!