Joining a Thread
You can block until another thread ends by calling Join:
class JoinDemo {
static void Main() {
Thread t = new Thread (delegate() { Console.ReadLine(); });
t.Start();
t.Join(); // Wait until thread t finishes
Console.WriteLine ("Thread t's ReadLine complete!");
}
}
The Join method also accepts a timeout argument – in milliseconds, or as a TimeSpan, returning false if the Join timed out rather than found the end of the thread. Join with a timeout functions rather like Sleep – in fact the following two lines of code are almost identical:
Thread.Sleep (1000);
Thread.CurrentThread.Join (1000);
(Their difference is apparent only in single-threaded apartment applications with COM interoperability, and stems from the subtleties in Windows message pumping semantics described previously: Join keeps message pumping alive while blocked; Sleep suspends message pumping).