Question

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?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top