问题
I have a form (complexForm in the code) with multiple controls which takes some time to load. So I decided to put in in a separate thread in order to decrease initial loading time. Everything works fine except the label control on the wait form ( Form1 in the code) doesn't show up initially; just a flash of a sec before Form1 went off. So my question is, why doesn't the label control show up?
[STAThread]
static void Main()
{
Thread thread = new Thread(delegate()
{
var wait = new Form1(); //simple form with a label control with text "please wait"
wait.Show();
var complexUI = new complexForm();// this takes long time to load
wait.Dispose();// it will go off even without this method
// MessageBox.Show("loaded");
});
thread.SetApartmentState(ApartmentState.STA);
thread.Priority = ThreadPriority.Highest;
thread.IsBackground = true;
thread.Start();
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new main());
}
回答1:
Do not do this. It'll end in tears. Only ever create UI controls from the UI thread - that's the thread that owns the message pump, which is crucial to proper operation.
The right solution to this is to create a Splash Screen which is shown while your main window is initialising.
There's quite a few threads on Stack Overflow about how to create a splash screen.
来源:https://stackoverflow.com/questions/14898986/controls-doesnt-show-if-run-on-a-background-thread-c-sharp-winform