c-sharp
  1. c-sharp-thread-join

C# Thread Join

In C#, it is common to work with multiple threads to perform parallel operations. When using threads, it is important to ensure that the main thread waits for all child threads to finish before exiting. In this tutorial, we'll discuss how to use the Join method to wait for a thread to complete in C#.

Syntax

The syntax for using the Join method to wait for a thread to complete in C# is as follows:

// Wait for a single thread to complete
thread.Join();

// Wait for multiple threads to complete
foreach (Thread t in threads) {
   t.Join();
}

The Join method is called on the thread you want to wait for, either a single thread or multiple threads in a loop.

Example

Let's say we want to create a program that performs a time-consuming operation on a separate thread. We can use the Join method to wait for the operation to complete before continuing. Here's how we can implement it:

static void Main(string[] args) {
   Thread t = new Thread(new ThreadStart(DoWork));
   t.Start();
   t.Join();
   Console.WriteLine("Operation completed");
   Console.ReadLine();
}

static void DoWork() {
   // perform time-consuming operation here
}

Now, when we run the program, the main thread will wait for the child thread to complete the operation before continuing.

Output

When we run the example code above, the output will be:

Operation completed

This is because the main thread waits for the child thread to complete the time-consuming operation before printing the message to the console.

Explanation

In the example above, we created a program that performs a time-consuming operation on a separate thread using the DoWork method. We used the Join method to wait for the operation to complete before continuing. We called the DoWork method on a new thread and used the Join method to wait for the child thread to complete before printing a message to the console.

Use

The Join method is useful when you want to ensure that a thread has completed its task before continuing with the main thread. You can use Join to wait for a single thread or multiple threads to complete before proceeding with your program.

Important Points

  • The Join method blocks the calling thread until the child thread has completed.
  • If the child thread throws an exception, the Join method will throw the same exception in the main thread.
  • If the child thread does not complete within a certain time period, you can pass a timeout value to the Join method to return control to the main thread after a specified time.

Summary

In this tutorial, we discussed how to use the Join method to wait for a thread to complete in C#. We covered the syntax, example, output, explanation, use, important points, and summary of using Join in C#. With this knowledge, you can now ensure that your main thread waits for all child threads to complete before continuing with your program.

Published on: