如何以编程方式找到 Control 所属的线程

发布于 2025-01-05 07:09:42 字数 223 浏览 2 评论 0原文

要求所有 .net 控件都在主线程上创建,至少如果意图将控件与界面集成(通常是这种情况),那么这是必要的。此外,要修改控件的属性,必须使用控件自己的调用方法从控件的线程调用该方法。

有没有办法查看控件并直接识别其所属线程?

另外或相反,是否可以检测当前线程是否是“主线程”? Visual Studio 识别为运行时可以看到的主线程的线程有什么特别之处吗?或者只是 VS 执行初始化调试的第一个线程?

It is a requirement that all .net Controls are created on the main thread, at least this is necessary if the intent is to integrate the control in with the interface which is usually the case. Additionally to modify properties on the control one must invoke the method from the control's thread using its own invoke method.

Is there a way to look at a control and identify its owning thread directly?

Additionally or conversely, is it possible to detect whether the current thread is the "Main thread"? Is there anything special about the thread that Visual Studio identifies as the main thread that can be seen at runtime, or is it simply that this is the first thread that VS executes to initialise debugging?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

最美的太阳 2025-01-12 07:09:42

另外或者相反,是否可以检测当前线程是否是“主线程”?

您可以使用 Control.InvokeRequired 来看看你是否在合适的线程上。如果不是,那么您应该使用 Control.InvokeControl.BeginInvoke 将调用编组回拥有线程。

Visual Studio 识别为运行时可见的主线程的线程有什么特别之处吗?或者只是 VS 执行初始化调试的第一个线程?

它实际上是用于创建 SynchronizationContext 的线程它正在处理 Windows 消息泵。此线程将(或应该)始终标记为 STA 线程(请参阅 Thread.ApartmentState),并运行适当的同步上下文和消息泵。 Application.Run 方法在普通 Windows 窗体应用程序的主线程中进行设置。

Additionally or conversely, is it possible to detect whether the current thread is the "Main thread"?

You can use Control.InvokeRequired to see if you're on the appropriate thread. If you are not, then you should use Control.Invoke or Control.BeginInvoke to marshal the call back to the owning thread.

Is there anything special about the thread that Visual Studio identifies as the main thread that can be seen at runtime, or is it simply that this is the first thread that VS executes to initialise debugging?

It's actually the thread that is used to create the SynchronizationContext which is handling the Windows Message pump. This thread will (or should) always be marked as an STA thread (see Thread.ApartmentState), and have the appropriate synchronization context and message pump running. The Application.Run method sets this up within the main thread in a normal Windows Forms application.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文