如何确定方法是否以解耦方式在 UI 线程上执行?
这是我遇到的问题:我需要确保在 UI 线程上实例化一个对象。 如果不是,它应该抛出异常。 但是如何在方法内部检查它是否在 UI 线程上运行? 注意:我不想将任何信息传递到对象的构造函数中。
完美的候选者是 DispatcherSynchronizationContext(SynchronizationContext 的 WPF 实现),它在内部保存对 Dispatcher 的引用,该引用引用与其关联的线程,但不幸的是该字段是私有的,因此我无法访问它。
Here is the problem I have: I need to make sure an object is instantiated on the UI thread. If it is not, it should throw an exception. But how do I check inside a method whether it is running on the UI thread? Note: I do not want to pass any information into the object's constructor.
The perfect candidate would be the DispatcherSynchronizationContext (WPF implementation of SynchronizationContext) which internally holds a reference to Dispatcher which references the thread it's associated with, but unfortunately that field is private so there is no way for me to access it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
需要澄清的是,虽然通常只有 1 个 UI 线程,但可以有多个 UI 线程。 对于 WPF 和 WinForms 都是如此。
我发现实现此目的的最佳方法是使用 SynchronizationContext。 WPF 和 WinForms 都将在它们运行 UI 的任何线程上建立 SynchronizationContext。 如果我不依赖于任何特定的 UI 模型,这就是我使用的函数。
请注意,它绝不是万无一失的。 非 UI 组件可以建立 SynchronizationContext,这对于简单的工作线程将返回 true。 因此有了非权威的名称。
一种稍微更可靠的方法如下。 但它要求您至少引用 WPF 的一部分来实现。
Small clarification, although there is typically only 1 UI thread there can be many UI threads. This is true for both WPF and WinForms.
The best way I've found to achieve this though is with a SynchronizationContext. Both WPF and WinForms will establish a SynchronizationContext on any thread they are running UI on. This is the function I use if I am not tied to any particular UI model.
Note, it is not in any way foolproof. It's possible for non-UI components to establish a SynchronizationContext and this would return true for a simple worker thread. Hence the non-authoritative name.
A slightly more reliable way to do this is as follows. But it requires you to reference at least a portion of WPF to implement.
Dispatcher.CheckAccess() 返回如果您的代码与调度程序在同一线程上运行,则为 true。 如果只有一个 Dispatcher/UIThread,它应该可以工作。
Dispatcher.CheckAccess() returns true if your code runs on the same Thread as the Dispatcher. It should work if there is only one Dispatcher/UIThread.