gpt4 book ai didi

c# - 如何获得特定WPF窗口的当前SynchronizationContext?

转载 作者:行者123 更新时间:2023-12-03 13:04:04 25 4
gpt4 key购买 nike

好吧,我有点困惑。查看与SynchronzationContext相关的代码,特别是在WPF中使用时,因此它实际上是DispatcherSynchronizationContext。以下是《 MSDN杂志》中有关此类的摘录:

DispatcherSynchronizationContext (WindowsBase.dll: System.Windows.Threading) WPF and Silverlight applications use a DispatcherSynchronizationContext, which queues delegates to the UI thread’s Dispatcher with “Normal” priority. This SynchronizationContext is installed as the current context when a thread begins its Dispatcher loop by calling Dispatcher.Run. The context for DispatcherSynchronizationContext is a single UI thread.

All delegates queued to the DispatcherSynchronizationContext are executed one at a time by a specific UI thread in the order they were queued. The current implementation creates one DispatcherSynchronizationContext for each top-level window, even if they all share the same underlying Dispatcher.


(从这里: https://msdn.microsoft.com/magazine/gg598924.aspx)
让我感到困惑的是,我用粗体显示/斜体显示的这两个部分彼此矛盾。第一个似乎说每个线程创建一个 DispatcherSynchronizationContext并将其设置为线程的当前同步上下文。但是,第二个摘录说,即使每个窗口都共享同一个调度程序/UI线程,每个窗口也会创建一个
我缺少/不了解什么?
如果确实每个窗口一个,而不是每个线程一个,那么如何获取特定窗口的DispatcherSynchronizationContext

最佳答案

在WPF中,SynchronizationContext本质上是Dispatcher的包装器。如果查看实现here,则可以看到PostSend方法包装了InvokeBeginInvoke

关于DispatcherSynchronizationContext的文档所指的是,它正在抓取当前的UI线程来完成工作,即使用

Application.Current.Dispatcher

SyncrhonizationContext实际上正在使用当前线程的调度程序,而不管它是否与UI相关。
Thread.CurrentContext

由于所有Windows都在UI线程上运行,因此无法为每个线程获取特定的 DispatcherSynchronizationContext

关于c# - 如何获得特定WPF窗口的当前SynchronizationContext?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36844382/

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