Creating a form on non-gui thread
You can't access gui controls from a thread they were not created on, at least so says the message of an exception that is sometimes raised when you do it.
Recently I was puzzled by seeing that forms created on background threads work just fine. My mental model was that all actions initiated by UI input is handled on the GUI thread. Clicking on a button on such a form should raise the dreaded exception (the form and all its controls were created on a background thread not the gui thread), but it 开发者_如何学编程doesn't. Something is wrong with my map.
(*) well to be honest I have seen one problem where opening the standard open file dialog was blocking everything
The restriction is that interaction with any UI element must happen on the tread that created it. This does not mean that you cannot create a form on a background thread. However, all interaction with that from must happen on that background thread. As long as you make sure to do this (by using InvokeRequired
and Invoke
as needed) you can go ahead and do this.
I have a sample of doing this in a blog post that I made a while ago.
The reason I didn't see anything going wrong was because the exception is only raised if you enable it. There is a static property on the Control called CheckForIllegalCrossThreadCalls, False by default. The doc says:
When a thread other than the creating thread of a control tries to access one of that control's methods or properties, it often leads to unpredictable results. A common invalid thread activity is a call on the wrong thread that accesses the control's Handle property. Set CheckForIllegalCrossThreadCalls to true to find and diagnose this thread activity more easily.
精彩评论