从一个给定的主题得到的SynchronizationContext主题、SynchronizationContext

2023-09-07 02:04:19 作者:  ゛我给不起你要的以后

我似乎无法找到如何让的SynchronizationContext 给定的:

I seem not to find how to get the SynchronizationContext of a given Thread:

Thread uiThread = UIConfiguration.UIThread;
SynchronizationContext context = uiThread.Huh?;

为什么我需要?

Why should I need that?

由于我需要张贴到UIThread从不同的地点横跨所有的前端应用程序。所以,我在一类称为 UIConfiguration 定义的静态属性。我设置该属性的 Program.Main 方法:

Because I need to post to the UIThread from different spots all across the front end application. So I defined a static property in a class called UIConfiguration. I set this property in the Program.Main method:

UIConfiguration.UIThread = Thread.CurrentThread;

在那一刻我可以肯定我有正确的线程,但我不能设置一个静态属性,如

In that very moment I can be sure I have the right thread, however I cannot set a static property like

UIConfiguration.SynchronizationContext = SynchronizationContext.Current

,因为WinForms的实施该类的尚未安装。由于每个线程都有它自己的SynchronizationContext,必须能够从给定的对象中检索它,还是我完全错了吗?

because the WinForms implementation of that class has not yet been installed. Since each thread has it's own SynchronizationContext, it must be possible to retrieve it from a given Thread object, or am I completely wrong?

推荐答案

这是不可能的。问题是,一个的SynchronizationContext 真是两个完全不同的概念。

This is not possible. The problem is that a SynchronizationContext and a Thread are really two completely separate concepts.

尽管这是事实,Windows窗体和WPF两者设置一个的SynchronizationContext 主线程,大多数其他线程没有。例如,没有在线程池线程都包含自己的SynchronizationContext(当然,除非你安装你自己的)。

While it's true that Windows Forms and WPF both setup a SynchronizationContext for the main thread, most other threads do not. For example, none of the threads in the ThreadPool contain their own SynchronizationContext (unless, of course, you install your own).

也有可能为的SynchronizationContext 是完全无关的线程和线程的。同步环境可以很容易地安装了同步到外部服务,或整个线程池等。

It's also possible for a SynchronizationContext to be completely unrelated to threads and threading. A synchronization context can easily be setup that synchronizes to an external service, or to an entire thread pool, etc.

在你的情况,我建议你最初,主窗体的加载事件中设置你的 UIConfiguration.SynchronizationContext 。上下文是保证在该点开始,并将无法使用,直到该消息泵在任何情况下被启动。

In your case, I'd recommend setting your UIConfiguration.SynchronizationContext within the initial, main form's Loaded event. The context is guaranteed to be started at that point, and will be unusable until the message pump has been started in any case.