Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
312 views
in Technique[技术] by (71.8m points)

.net - Dispatcher.CurrentDispatcher vs. Application.Current.Dispatcher

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?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...