Pass parameter to thread in C# interview question – If we want to pass parameter to thread, How would you do that? We need to explain by a thread program example.

Answer: Argument / parameter to a thread function can be passed in multiple ways and here is the 2 ways to pass parameter to a thread in C#

  • Using parameter in Thread.Start() method
  • Using ParameterizedThreadStart class delegate.

Pass parameter to thread in C# – 2 ways

Passing parameter to a thread is actually very simple. Lets see 2 ways with program example in C#

1- Using Thread.Start() method:

In this method,first of all, create a thread in c# program and assign a user defined thread function to the thread [new Thread(threadFunc)] and pass argument to thread Start(arg) method.

In fact, in C# thread, Start() overloaded methods are available. e.g. Start() and Start(Object) etc. and to pass parameter to thread in C#, we can  use overloaded  Start(Object).

Program Example – Using Thread.Start(Object) method in C#:

using System;
using System.Threading;


namespace parameter_to_thread_function
{
    class Program
    {
        static void Main(string[] args)
        {
            String arg = "Interview Sansar !!!";

            //Create a thread
            Thread tParm = new Thread(threadFunc);
            //Start thread execution
            tParm.Start(arg);//pass argument using Start(Object) method overload
        }

        //Thread function
        static void threadFunc(object arg)
        {
            Console.WriteLine(arg);
        }
    }
}

2- Using ParameterizedThreadStart delegate:

Pass user defined thread function to ParameterizedThreadStart delegate and assign delegate object to Thread class object. e.g.  Thread(new ParameterizedThreadStart(threadFunc)). As a next step, call Start(arg) thread function.

Program Example – Using ParameterizedThreadStart delegate:
using System;
using System.Threading;


namespace parameter_to_thread_function
{
    class Program
    {
        static void Main(string[] args)
        {
            String arg = "Interview Sansar !!!";

            //Create object of ParameterizedThreadStart
            //pass it to Thread class constructor
            //Call Start() method with argument
            Thread tParm = new Thread(new ParameterizedThreadStart(threadFunc));
            tParm.Start(arg);//pass argument using Start(Object) method
        }

        //Thread function
        static void threadFunc(object arg)
        {
            Console.WriteLine(arg);
        }

    }
}

Related Posts