controls doesn't show if run on a background thread ( c# winform)

*爱你&永不变心* 提交于 2021-02-05 09:46:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!