Dot Net For All

How to wait for Thread in C#

There could be many scenarios where we need to wait for the thread in C#. And unless and until that thread is not complete we don’t continue with other thread.

Wait for Thread to complete

Below is the sample code to wait for Thread.

 static void Main(string[] args)
        {
            WriteLine("Starting...");
            Thread t = new Thread(PrintNumbersWithDelay);
            t.Start();
            t.Join();
            WriteLine("Thread completed");
        }

        static void PrintNumbersWithDelay()
        {
            WriteLine("Starting...");
            for (int i = 1; i < 10; i++)
            {
                Sleep(TimeSpan.FromSeconds(2));
                WriteLine(i);
            }
        }

In the above code I have created a Thread t and provided a method PrintNumbersWithDelay. In the method I am blocking the thread by Sleep method.

Now the main thread will wait unless the Thread t is not complete.

The output of the code would be like below.

How it works

When the program is run, it runs a long-running thread that prints out numbers and waits two seconds before printing each number.

But, in the main program, we called the t.Join method, which allows us to wait for the thread t to complete working.

When it is complete, the main program continues to run.

With the help of this technique, it is possible to synchronize execution steps between two threads. The first one waits until another one is complete and then continues to work. While the first thread waits, it is in a blocked state (as it is in the previous recipe when you call Thread.Sleep).

Top career enhancing courses you can't miss

My Learning Resource

Excel your system design interview