【问题标题】:how to know if thread execution is terminated?如何知道线程执行是否终止?
【发布时间】:2011-11-18 10:50:17
【问题描述】:

我有一个线程:

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

知道线程是否终止的最好方法是什么? 我正在寻找如何执行此操作的示例代码。 提前致谢。

【问题讨论】:

    标签: c# .net multithreading


    【解决方案1】:
    【解决方案2】:

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

    您可以使用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();
    

    【讨论】:

    • 通常回调方法会尝试做一个跨线程操作,比如更新 UI 指定进程完成。如果您的 UI 控件不支持跨线程操作,您将收到一个 InvalidOperationException 说明该控件是从创建它的线程以外的线程访问的,这可以通过调用像这样的回调方法来避免 this.Invoke(finished);跨度>
    【解决方案3】:

    如果你只是想等到线程完成,你可以使用。

    th.Join();
    

    【讨论】:

      【解决方案4】:

      只需使用 Thread.join() 正如哈拉姆所说。 检查此链接以获得更清晰的信息: http://msdn.microsoft.com/en-us/library/95hbf2ta.aspx

      使用此方法可确保线程已终止。来电者将 如果线程没有终止,则无限期阻塞。如果线程有 调用 Join 时已经终止,方法返回 马上。

      【讨论】:

        猜你喜欢
        • 2013-04-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-03
        • 1970-01-01
        • 1970-01-01
        • 2019-10-31
        • 1970-01-01
        相关资源
        最近更新 更多