Thread.Join方法在c#中有什么意义?

时间:2010-03-19 10:43:56

标签: c# multithreading

Thread #Join方法在c#中有什么意义?

MSDN表示它会阻塞调用线程,直到线程终止。有人可以用一个简单的例子来解释这个吗?

7 个答案:

答案 0 :(得分:14)

Join()基本上是while(thread.running){}

{
  thread.start()
  stuff you want to do while the other thread is busy doing its own thing concurrently
  thread.join()
  you won't get here until thread has terminated.
} 

答案 1 :(得分:8)

int fibsum = 1;

Thread t = new Thread(o =>
                          {
                              for (int i = 1; i < 20; i++)
                              {
                                  fibsum += fibsum;
                              }
                          });

t.Start();
t.Join(); // if you comment this line, the WriteLine will execute 
          // before the thread finishes and the result will be wrong
Console.WriteLine(fibsum);

答案 2 :(得分:3)

假设您有一个主线程将一些工作委托给工作线程。主线程需要工作人员正在计算的一些结果,因此在所有工作线程完成之前它不能继续。

在这种情况下,主线程将在每个工作线程上调用Join()。在返回所有Join()个调用之后,主线程知道所有工作线程都已完成,并且计算结果可供其使用。

答案 3 :(得分:3)

想象一下,您的程序在Thread1中运行。然后你需要开始一些计算或处理 - 你开始另一个线程 - Thread2。然后,如果您希望Thread1等到Thread2结束,则执行Thread1.Join();并且Thread1将不会继续执行,直到Thread2完成。

以下是MSDN中的说明。

答案 4 :(得分:3)

简单的示例方法:

public static void Main(string[] args)
{
    Console.WriteLine("Main thread started.");

    var t = new Thread(() => Thread.Sleep(2000));

    t.Start();

    t.Join();

    Console.WriteLine("Thread t finished.");
}

程序首先将消息打印到屏幕,然后启动一个新的线程,在终止之前暂停2秒钟。最后一条消息仅在t线程执行完毕后打印,因为Join方法调用会阻塞当前线程,直到t线程终止。

答案 5 :(得分:1)

static void Main()
{
 Thread t = new Thread(new ThreadStart(some delegate here));
 t.Start();
 Console.WriteLine("foo");
 t.Join()
 Console.WriteLine("foo2");
}

在你的代表中你会有另外一个这样的电话:

Console.WriteLine("foo3");

输出是:

foo
foo3
foo2

答案 6 :(得分:0)

这只是为了解释现有的答案,它解释了Join的作用。

调用Join还有允许消息泵处理消息的副作用。有关这可能相关的情况,请参阅此knowledge base article