wpf 如何获取 UI 线程的 Dispatcher?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2663070/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 21:41:37  来源:igfitidea点击:

How do I get the UI thread's Dispatcher?

wpfmultithreadingdispatcher

提问by Peter

Is there any way to get the UI thread's Dispatcherwhen you have no reference to any UI elements?

Dispatcher当您没有引用任何 UI 元素时,有没有办法获取 UI 线程?

回答by Abe Heidebrecht

You can grab the UI Dispatcher from the static application instance: Application.Current.Dispatcher

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

You may want to check Application.Currentfor null first, as it can be cleared during a shutdown sequence.

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

回答by M Townsend

The following works much better for me when being used in a WinForms application that happens to be also using WPF (in my case Esri's Arcmap.exe)

当在碰巧也使用 WPF 的 WinForms 应用程序中使用时,以下对我来说效果更好(在我的情况下是 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;

The other method (which involved calling new System.Windows.Application()to populate System.Windows.Application.Current) caused issues for me every time I opened a new WPF window and then closed it. Not only did this null out System.Windows.Application.Current, but I could no longer open up new windows as their InitializeComponents()methods, all failed with:

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

System.InvalidOperationException: 'The Application object is being shut down.'

System.InvalidOperationException: '应用程序对象正在关闭。'

So far the new solution is working without those side effects.

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