gpt4 book ai didi

.net - Dispatcher.CurrentDispatcher 与 Application.Current.Dispatcher

转载 作者:行者123 更新时间:2023-12-02 00:51:22 30 4
gpt4 key购买 nike

Dispatcher.CurrentDispatcher(在System.Windows.Threading中)和Application.Current.Dispatcher(在 >系统.Windows)?

我的直觉告诉我,Application.Current.Dispatcher永远不会改变,并且对于当前应用程序中的所有线程来说是全局的,而Dispatcher.CurrentDispatcher可能会创建一个新实例Dispatcher 的数量取决于调用它的线程。

正确吗?

如果是,Dispatcher.CurrentDispatcher 的用途是否主要用于多线程 UI?

最佳答案

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.

这是正确的。

此外,从非 UI 线程访问 Dispatcher.CurrentDispatcher 是没有任何意义的。除非你调用Dispatcher.Run,否则它不会执行任何操作。 ,并且进入无限消息循环并不是您想要在工作线程内执行的操作。

所以:

  • 在最常见的场景中,您的应用只有一个 UI 线程:Application.Current.DispatcherDispatcher.CurrentDispatcher UI 线程中的 code> 将返回相同的实例。您使用哪一个只是一个偏好问题。

  • 如果您的应用有多个 UI 线程,则每个 DispatcherObject将与构造时创建的 UI 线程的调度程序永久关联。在这种情况下,Application.Current.Dispatcher 将引用您的应用程序生成的线程的调度程序;您将无法使用它向其他 UI 线程拥有的控件发布消息。

关于.net - Dispatcher.CurrentDispatcher 与 Application.Current.Dispatcher,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10448987/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com