Thread.Join
MSDN解释为:使用此方法确保线程已终止。如果线程不终止,则调用方将无限期阻塞。如果调用 Join 时该线程已终止,此方法将立即返回。
如下边这个例子,
1 static void Main() 2 { 3 // Create the worker thread object. This does not start the thread. 4 Thread workerThread = new Thread(workMethod); 5 6 // Start the worker thread. 7 workerThread.Start(); 8 workerThread.Join(); 9 Console.WriteLine("Main thread: worker thread has terminated."); 10 Console.Read(); 11 } 12 static void workMethod() 13 { 14 Console.WriteLine("Work thread:start sleep"); 15 Thread.Sleep(1000); 16 Console.WriteLine("Work thread:finished sleep 1000"); 17 }
输出结果为:
如果去掉第8行,workerThread.Join(); 则输出结果为:
因为主线程中在workthread启动后的代码会直接执行完,而如果有workerThread.Join();则会将主线程中的剩余代码阻断,直到workerThread执行完后再继续执行