2013-02-15 35 views
0

我有一個窗體(complexForm在代碼中)與多個控件,需要一些時間來加載。所以我決定放入一個單獨的線程,以減少初始加載時間。除了等待表單上的標籤控件(代碼中的Form1)一開始不會顯示,一切正常;在Form1出發之前只需要一秒鐘的時間。所以我的問題是,爲什麼不顯示標籤控制?控件不顯示,如果運行在後臺線程(c#winform)

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

} 
+0

如果您使用多個'thread',爲什麼要將'ApartmentState'設置爲單線程('[STAThread]'和'ApartmentState.STA')? – Brian 2013-02-15 16:35:13

+0

你想實現什麼? 'var complexUI = new complexForm(); //這需要很長時間才能加載'在complexForm構造函數中執行什麼操作會導致長時間加載? – 2013-02-15 16:37:00

+0

實際上,我有DevExpress richeditcontrols在其中需要很長時間才能加載的ribbonbar。請參閱此URL http://www.devexpress.com/Support/Center/p/Q406398.aspx – user1746821 2013-02-15 16:42:43

回答

1

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

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

關於如何創建啓動畫面,Stack Overflow上有相當多的線程。

+0

我知道啓動畫面的方法。只是好奇這個線程http://www.devexpress.com/Support/Center/p/Q406398.aspx – user1746821 2013-02-15 16:44:17