簡體   English   中英

控件不顯示是否在后台線程上運行(c#winform)

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

我有一個帶有多個控件的表單( 代碼中的complexForm ),這需要一些時間才能加載。 因此,我決定放入一個單獨的線程中,以減少初始加載時間。 一切正常,除了等待表單(代碼中的Form1 )上的標簽控件最初沒有顯示; 在Form1關閉之前僅一秒鍾的時間。 所以我的問題是,為什么標簽控件不顯示?

[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());

}

不要這樣做。 它會以眼淚結束。 僅從UI線程創建UI控件-UI線程是擁有消息泵的線程,這對於正確操作至關重要。

正確的解決方案是創建一個啟動屏幕,該屏幕在初始化主窗口時顯示。

關於如何創建啟動畫面,Stack Overflow上有很多線程。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM