![]() |
VOOZH | about |
In C#, multiple threads can be created and run concurrently to perform parallel tasks. Sometimes it is necessary to wait for one thread to finish its execution before proceeding or for all threads to complete before continuing further. The Thread.Join() method allows one thread to wait for another thread's completion, ensuring proper synchronization.
The Join method of the Thread class waits for the thread to complete its execution before continuing with the execution of the calling thread. This method blocks the calling thread until the target thread has completed its execution.
Syntax:
public void Join();
public bool Join(int millisecondsTimeout);
public bool Join(TimeSpan timeout);
Example:
Thread 2 started. Thread 1 started. Main Thread execution completed.
Thread class provides the Join() method, which allows one thread to wait until another thread completes its execution. If "t" is a Thread object, "t.Join()" causes the current thread to pause its execution until the thread represented by "t" terminates. There are some versions of in Join() method which provide more control on Threads. The Join() method has the following overloads:
This method blocks the calling thread until the thread represented by this instance terminates while continuing to perform standard COM (Component Object Model) and SendMessage pumping.
Syntax:
public void Join ();
This method blocks the calling thread for the specified number of milliseconds or until the target thread terminates, whichever occurs first. Returns true if the target thread terminates before the timeout expires, false otherwise.
Syntax:
public bool Join (int millisecondsTimeout);
This method blocks the calling thread for the specified duration or until the target thread terminates, whichever occurs first. Returns true if the target thread terminates before the timeout expires, false otherwise.
Syntax:
public bool Join (TimeSpan timeout);
Example 1:
0 1 2 3 2nd thread is Working..
Explanation: In the above example,
Example 2:
New thread is terminated
The WaitAll method of the Task class waits for all the specified tasks to complete before continuing with the execution of the calling thread. This method blocks the calling thread until all the specified tasks have completed their execution.
Example:
Task 1 is running. Task 2 is running. Main Thread execution completed.