2010-03-19 25 views

回答

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. 
} 
3

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

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

3

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

这是描述MSDN

+0

MSDN说那里“阻塞调用线程,直到一个线程终止,同时继续执行标准COM和SendMessage泵。”执行标准COM有什么意义? sendMessage抽水的意义是什么? – Techee 2010-03-19 12:06:31

+2

实际上,这是不正确的。如果您希望'Thread1'等到'Thread2'结束,则执行'Thread2.Join()',而不是'Thread1.Join()'。 – d7samurai 2014-02-01 17:59:07

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线程终止。

+0

这很简单,但也相当无用:一个Thread.Start紧跟着一个Thread.Join,它使用第二个线程的整个目的失败。 (我知道这是一个玩具的例子,但仍然...) – Heinzi 2010-03-19 11:03:12

+1

@ Heinzi,它只是按要求演示了'Join'方法的基本行为。它从来没有打算描绘一个真实世界的场景。 – 2010-03-19 11:26:46

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 
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); 
0

这只是添加到现有的答案,这解释了什么Join做什么。

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