Here’s a simplified example of what I’m trying to do:
I have 2 controls MyControl c and Panel p. p is created in the main GUI thread as normal, but I want c to be created in a background thread, because it takes awhile and I don’t want to freeze the GUI. How can I add c to p.Controls? If I do it in this.Invoke it throws an exception for c, and if I do it from the background thread it throws an exception for p.
Or is it that I really shouldn’t be creating GUI elements outside of the main GUI thread?
Yes, this is basically the problem. Most controls have thread affinity, and must be created within the user interface thread.
Typically, the way to handle this is to move the “work” that is causing the control creation to be slow onto a background thread, but still create the control on the UI thread. You’d then use Control.Invoke or Control.BeginInvoke to update the information in the UI once the slow work was completed.
For example, if you’re loading a set of data from some external source, you can create the control, and start a background thread to load the data. Once the data is loaded, you can then update the control to reflect it. This will cause it to stay responsive the entire time.