我有一個線程:如何知道線程執行是否終止?
private void start_Click(object sender, EventArgs e) {
//...
Thread th = new Thread(DoWork);
th.Start();
}
什麼知道,如果線程終止的最好方法? 我正在尋找一個示例代碼如何做到這一點。 在此先感謝。
我有一個線程:如何知道線程執行是否終止?
private void start_Click(object sender, EventArgs e) {
//...
Thread th = new Thread(DoWork);
th.Start();
}
什麼知道,如果線程終止的最好方法? 我正在尋找一個示例代碼如何做到這一點。 在此先感謝。
有幾件簡單的事情你可以做。
您可以使用Thread.Join
來查看線程是否已經結束。
var thread = new Thread(SomeMethod);
thread.Start();
while (!thread.Join(0)) // nonblocking
{
// Do something else while the thread is still going.
}
當然,如果你不指定超時參數,然後調用線程將阻塞,直到工作線程結束。
您也可以在入口點方法結束時調用委託或事件。
// This delegate will get executed upon completion of the thread.
Action finished =() => { Console.WriteLine("Finished"); };
var thread = new Thread(
() =>
{
try
{
// Do a bunch of stuff here.
}
finally
{
finished();
}
});
thread.Start();
如果你只是想等到線程完成就可以使用。
th.Join();
只需使用 Thread.join()
作爲harlam說。 再檢查一下這個鏈接,更清晰: http://msdn.microsoft.com/en-us/library/95hbf2ta.aspx
使用此方法來確保線程終止。如果線程沒有終止,調用者將無限期地阻止 。如果線程在調用Join時已經終止 ,則該方法立即返回 。
通常情況下,回調方法會盡量做到像 一個跨線程操作更新UI指定過程完成。如果你的UI控件不支持交叉線程操作,你會得到一個InvalidOperationException異常,說該控件是從一個線程訪問的,而不是它創建的線程,這可以通過調用回調方法來避免,如這個 這個。調用(成品);' –