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

本文关键字:是否 终止 执行 线程 何知道 | 更新日期: 2023-09-27 18:14:55

我有一个线程:
private void start_Click(object sender, EventArgs e) {
   //...
   Thread th = new Thread(DoWork);
   th.Start(); 
}

知道线程是否终止的最好方法是什么?我正在寻找一个示例代码如何做到这一点。

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

线程状态

http://msdn.microsoft.com/en-us/library/system.threading.threadstate.aspx

你可以做一些简单的事情。

您可以使用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时已经终止,该方法返回立即.