Thread.Join Method
Blocks the calling thread until a thread terminates, while continuing to perform standard COM and SendMessage pumping.
Namespace: System.Threading
Assembly: mscorlib (in mscorlib.dll)
| Exception | Condition |
|---|---|
| ThreadStateException | The caller attempted to join a thread that is in the ThreadState.Unstarted state. |
| ThreadInterruptedException | The thread is interrupted while waiting. |
Use this method to ensure a thread has terminated. The caller will block indefinitely if the thread does not terminate. If the thread has already terminated when Join is called, the method returns immediately.
This method changes the state of the calling thread to include ThreadState.WaitSleepJoin. You cannot invoke Join on a thread that is in the ThreadState.Unstarted state.
Note |
|---|
The HostProtectionAttribute attribute applied to this type or member has the following Resources property value: Synchronization | ExternalThreading. The HostProtectionAttribute does not affect desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes. |
The following example shows how to use Join to wait for a thread to terminate, and demonstrates that the order of joins doesn't matter. The example starts two threads. The first thread sleeps for 4 seconds, displays a message, and terminates. The second thread sleeps only for 1 second. The example calls Join on the first thread and then on the second thread.
using System; using System.Threading; class Example { static void Main() { Thread t1 = new Thread(() => { Thread.Sleep(4000); Console.WriteLine("t1 is ending."); }); t1.Start(); Thread t2 = new Thread(() => { Thread.Sleep(1000); Console.WriteLine("t2 is ending."); }); t2.Start(); t1.Join(); Console.WriteLine("t1.Join() returned."); t2.Join(); Console.WriteLine("t2.Join() returned."); } } /* This example produces the following output: t2 is ending. t1 is ending. t1.Join() returned. t2.Join() returned. */
Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)
The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Note