如何知道线程执行是否终止?

我有一个post:

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()作为哈拉姆说。 切换此链接以获得更清晰: http : //msdn.microsoft.com/en-us/library/95hbf2ta.aspx

使用此方法可确保线程已终止。 如果线程没有终止,调用者将无限期地阻塞。 如果在调用Join时线程已经终止,则该方法立即返回。