2012-11-06 41 views
0

我使用主窗體和顯示進度的另一種窗體開發多線程應用程序。 起初:我在MainForm中從另一個線程的主線程中顯示錶格

Progress p=new Progress(); 

二創建ProgressForm:我(在我的應用程序蒙山所有數據)創建類模型的新實例。

Model m = new Model(); 

和訂閱事件:

m.OperationStarted += new EventHandler(OnCopyStarted); 

private void OnCopyStarted(object sender, EventArgs e) 
{ 
    p.Show(); 
} 

第三:我運行在另一個線程一些操作,我在另一型號

private bool isStarted; 
      public bool IsStarted 
      { 
       get{return isStarted;} 
       set 
       { 
        isStarted = value; 
        if (isStarted && OperationStarted != null) 
        { 
         OperationStarted(this, EventArgs.Empty); 
        } 
       } 
      } 

我questoin更改屬性是:爲什麼進展形式是不在主線程中顯示?我如何在沒有鎖定的情況下運行它?

+0

這些片段似乎與問題沒有多大關係。在主線程訂閱事件之前,可能的失敗模式是過早地啓動線程。使用調試器。 –

+0

我認爲你可以/應該只在主線程中創建和訪問UI元素?!? –

回答

2

所有的UI操作必須在主UI線程上運行。

OnCopyStarted方法正在另一個線程上調用,所以它必須在顯示對話框之前切換到UI線程。

您可以使用表單的BeginInvoke切換到UI線程。如:

void OnCopyStarted(object sender, EventArgs e) 
{ 
    p.BeginInvoke((Action) (() => p.Show())); 
} 
2

試試:

var t = new Thread(() => { 
      Application.Run(new Progress()); 
     }); 
t.Start(); 
相關問題