WPF 可以/是否有多个 GUI 线程?
WPF 可以/是否有多个 GUI 线程?或者它总是只有一个 GUI 线程(即使我有多个窗口/对话框)?
我这样问是因为我有来自其他线程的事件,并且我想在 GUI 线程中处理它们(因为我需要根据事件修改主窗口的控件)。
顺便说一句:我知道我需要使用 Dispatcher
对象来实现此目的。因此,我可以重新表述我的问题并询问:WPF 中的所有 GUI 元素是否始终只有一个 Dispatcher
对象?
Can/Does WPF have multiple GUI threads? Or does it always only have one GUI thread (even if I have multiple windows/dialogs)?
I'm asking because I have events coming from other threads and I'd like to handle them in the GUI thread (because I need to modify the controls of my main window accordings to the events).
Btw: I know I need to use a Dispatcher
object for this purpose. So, I could rephrase my question and ask: Is there always only one Dispatcher
object for all GUI elements in WPF?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
基于 http://eprystupa .wordpress.com/2008/07/28/running-wpf-application-with-multiple-ui-threads/ 我自己做了一些验证。我想在这里分享结果。首先:
可以有多个 GUI 线程(因此可以有多个
Dispatcher
实例)。但是:
只需创建一个新窗口(模式或非模式)不创建新的GUI线程。需要显式创建线程(通过创建
Thread
的新实例)。注意: 模式对话框可能不是使用单独的线程,而是使用 Dispatcher.PushFrame() 阻止此方法的调用者,同时仍允许分派事件。
我创建了一个简单的 WPF 类(再次基于第一个答案中的链接)来验证所有这些内容。我在这里分享它,这样你就可以尝试一下。
MainWindow.xaml:
MainWindow.xaml.cs:
Based on http://eprystupa.wordpress.com/2008/07/28/running-wpf-application-with-multiple-ui-threads/ I did some verification on my own. I'd like to share the results here. First of all:
There can be multiple GUI threads (and therefor multiple
Dispatcher
instances).However:
Simply creating a new window (modal or not) does not create a new GUI thread. One needs to create the thread explicitly (by creating a new instance of
Thread
).Note: Instead of using separate threads, modal dialogs are likely being realized by using Dispatcher.PushFrame() which blocks the caller of this method while still allowing events to be dispatched.
I've created a simple WPF class (again, based on the link from the first answer) to verify all this stuff. I share it here so you can play around with it a little bit.
MainWindow.xaml:
MainWindow.xaml.cs: