2010-03-19 62 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