Software & Finance





C# - Wait for new thread to join Main Thread





I have given a simple C# program to start a new thread and wait for the main thread to join the worker threads.


System.Threading.Thread is the class you want to use to create a thread. When you instantiate System.Threading.Thread the class you can pass two kinds of delegate.

System.Threading.ThreadStart and System.Threading.ParameterizedThreadStart

 

The join function from System.Threading.Thread will block the main thread and wait for the worker thread to complete its task.

 

Here is the sample code:

 

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading;

 

namespace ConsoleApplication1

{

    class Program

    {

        static public void ProcessFromThread()

        {

            for (int i = 0; i < 10; i++)

            {

                Thread.Sleep(100);

                Console.WriteLine(i * 100);

            }

        }

 

        static public void ProcessFromThreadWithObj(Object obj)

        {

            for (int i = 0; i < 10; i++)

            {

                Thread.Sleep(100);

                Console.WriteLine(obj.ToString());

            }

        }

 

 

        static void Main(string[] args)

        {

            System.Threading.ThreadStart threadfunction = ProcessFromThread;

            System.Threading.ParameterizedThreadStart theadfunctionWithParams = ProcessFromThreadWithObj;

 

            System.Threading.Thread myThread = new System.Threading.Thread(threadfunction);

            myThread.Start();

 

            System.Threading.Thread myThreadParms = new System.Threading.Thread(theadfunctionWithParams);

          

            myThreadParms.Start("With Params");

 

            myThread.Join();

            myThreadParms.Join();

 

            System.Console.WriteLine("End of Threads");

        }

    }

}

 

Output:

 

With Params
With Params
100
With Params
200
300
With Params
400
With Params
500
With Params
600
With Params
700
With Params
800
With Params
900
With Params
End of Threads
Press any key to continue . . .