C# – join() method

join():

  • An instance method belongs to Thread class.
  • It stops the current the thread execution until joined thread execution completes.

Example: Consider First thread is calculating sum of first N numbers and second thread has to display the result. The Second thread has to wait until First thread completes calculation.

using System;
using System.Threading;
public class Program
{
            public static int n;
            static void Main(string[] args)
            {
                        Console.WriteLine(“Enter n value : “);
                        Program.n = Convert.ToInt32(Console.ReadLine());
                        Thread t = new Thread(new ThreadStart(Calculation.find));
                        t.Start();
                        t.Join();
                        Console.WriteLine(“Sum of First : ” + n + ” numbers is : ” + Calculation.sum);
            }
}
 
public class Calculation
{
            public static int sum = 0;
            public static void find()
            {
                        for(int i=1; i<=Program.n; i++)
                        {
                                    Calculation.sum = Calculation.sum + i;
                        }
            }
}
Scroll to Top