我如何获得UI线程Dispatcher?

问题描述 投票:49回答:2

当你没有引用任何UI元素时,有没有办法获得UI线程的Dispatcher

wpf multithreading dispatcher
2个回答
92
投票

您可以从静态应用程序实例中获取UI Dispatcher:Application.Current.Dispatcher

您可能希望首先检查Application.Current是否为null,因为它可以在关闭序列期间清除。


1
投票

当在WinForms应用程序中使用时,以下工作对我来说更好,它恰好也使用WPF(在我的案例中是Esri的Arcmap.exe)

private System.Windows.Threading.Dispatcher Dispatcher { get; set; }

// I put this in my view model constructor as it MUST be called from UI thread
Dispatcher = System.Windows.Threading.Dispatcher.CurrentDispatcher;

另一种方法(涉及调用new System.Windows.Application()来填充System.Windows.Application.Current)每次打开一个新的WPF窗口然后关闭它时都会给我带来问题。这不仅使System.Windows.Application.Current无效,而且我再也无法打开新的窗口,因为他们的InitializeComponents()方法,都失败了:

System.InvalidOperationException:'正在关闭Application对象。'

到目前为止,新的解决方案正在没有那些副作用。

© www.soinside.com 2019 - 2024. All rights reserved.