如何知道线程执行是否终止? [英] how to know if thread execution is terminated?

查看:117
本文介绍了如何知道线程执行是否终止?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个线程:

private void start_Click(object sender, EventArgs e) {
   //...
   Thread th = new Thread(DoWork);
   th.Start(); 
}

了解线程是否终止的最佳方法是什么? 我正在寻找示例代码如何执行此操作. 预先感谢.

what's the best way to know if thread is terminated? I'm looking for an example code how do this. Thanks in advance.

推荐答案

您可以做一些简单的事情.

There are few simple things you can do.

您可以使用Thread.Join查看线程是否已结束.

You could use Thread.Join to see if the thread has ended.

var thread = new Thread(SomeMethod);
thread.Start();
while (!thread.Join(0)) // nonblocking
{
  // Do something else while the thread is still going.
}

当然,如果您未指定超时参数,则调用线程将阻塞,直到工作线程结束.

And of course if you do not specify a timeout parameter then the calling thread will block until the worker thread ends.

您还可以在入口点方法的末尾调用委托或事件.

You could also invoke a delegate or event at the end of entry point method.

// 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();

这篇关于如何知道线程执行是否终止?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆