如何以编程方式找到 Control 所属的线程
要求所有 .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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用 Control.InvokeRequired 来看看你是否在合适的线程上。如果不是,那么您应该使用 Control.Invoke 或 Control.BeginInvoke 将调用编组回拥有线程。
它实际上是用于创建 SynchronizationContext 的线程它正在处理 Windows 消息泵。此线程将(或应该)始终标记为 STA 线程(请参阅 Thread.ApartmentState),并运行适当的同步上下文和消息泵。
Application.Run
方法在普通 Windows 窗体应用程序的主线程中进行设置。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.
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.