Are there any problems with having a group of win forms in one thread and another group in another thread?
I have an application that has two distinct groups of win forms and I want each group to operate in separate threads. Are there any problems with this approach as long as I BeginInvoke/Invoke when operations happen across the different threads?
This question stems from the fact that I've always been used to thinking in terms of a 'gui thread' that I must if (InvokeRequired) { Invoke } else { ... }
and all forms live on that thread.
An alternative angle on this question:
Is there anythi开发者_StackOverflow社区ng 'special' about the default thread that win forms exist in or is it the same as any other thread?
Well, there are ways to shoot the foot but Windows Forms rarely forgets to tell you about it.
Yes, there's something special about the "main thread". It runs in STA mode, a Single Threaded Apartment. It is a mode that affects COM components, the shell dialogs like OpenFileDialog and operations like Drag + Drop and the Clipboard. Threads that display a UI always must be STA. That's automatic in normal WF apps with the [STAThread] attribute on the Main() method. In your own app you have to call Thread.SetApartmentState() before you start it. And the thread is special because it pumps a message loop (Application.Run), a requirement for STA threads.
By default, any Thread you start or any threadpool thread runs in MTA mode. Threadpool threads cannot be changed, they are always MTA.
It should work just fine, I am pretty sure that in my current project it is implemented this way and we didn't see any issues with this. You just need to remember to use the correct control when you use InvokeRequired and Invoke methods.
A GUI thread simply pumps messages so that it can process the standard Windows messages, I don't think there is anything else special about it.
the only problem that I can think of is related to very very old COM components, that are related to the main single threading apartment.
msdn.microsoft.com
but this is very unlikely
精彩评论