2012-03-10 22 views
1
private void showStatistics(string path) 
{ 
    Thread thread = new Thread(() => 
     { 
      Statistics myClass= new Statistics(path); 
      list = myClass.getStatistics(); 
     }); 

    thread.Start(); 

    foreach (KeyValuePair<string, string> item in list) 
    { 
     listBoxIps.Items.Add(item.Key + item.Value + "\n"); 
    } 
} 

我想等到線程完成自己的工作,然後啓動foreach,當我把foreach在線程,收十字線程錯誤。如何要等到我的線程完成

回答

2

你想要thread.Join。但這可能不是你想要做的(因爲Join會阻止,在這種情況下爲什麼甚至首先使用單獨的線程)。看看BackgroundWorker課程。

+1

另外,看看並理解Form.Invoke。你可以讓你的線程在完成時調用窗體中的一個方法,但是它必須使用Invoke來執行......如果你的'後線程邏輯'對任何控件做任何事情。 – sethcall 2012-03-10 16:54:02

+0

感謝其與BackgroundWorker的良好合作 – user979033 2012-03-10 17:04:51

0

創建共享變量,並用它來表示線程完成。在循環中,線程啓動之後,執行:

while (!finished) 
{ 
    Application.DoEvents(); 
    Thread.Sleep(10); 
} 

你的問題是,你希望在list充滿你的UI來響應。這將確保它。

1

要等待Thread完成,您可以使用Join API。但是,在這種情況下,這可能不是您想要的。這裏的Join會導致整個UI阻塞,直到完成Thread這將破壞首先使線程的目的。

另一種設計是產生Thread,並讓它通過BeginInvoke完成後回撥到UI中。假設getStatistics返回List<KeyValuePair<string, string>

private void showStatistics(string path) { 
    Action<List<KeyValuePair<string, string>> action = list => { 
    foreach (KeyValuePair<string, string> item in list) { 
     listBoxIps.Items.Add(item.Key + item.Value + "\n"); 
    } 
    }; 

    Thread thread = new Thread(() => { 
    Statistics myClass= new Statistics(path); 
    list = myClass.getStatistics(); 
    this.BeginInvoke(action, list); 
    }); 
}