ThreadStart
This specifies a target method. It does not support any arguments to the method. We use ThreadStart
to begin running a thread.
ThreadStart
typeWe create an instance of it and pass that to the Thread constructor. We also use ParameterizedThreadStart
.
This example C# program creates an array of 4 different threads. It starts a parameterless method on each thread. It then joins the threads together in a sequential order.
ThreadStart
is created with a constructor that receives a target function name. This target method must not receive any parameters.ThreadStart
instance is passed as an argument to the Thread constructor.using System; using System.Threading; class Program { static void Main() { // Create an array of Thread references. Thread[] array = new Thread[4]; for (int i = 0; i < array.Length; i++) { // Start the thread with a ThreadStart. ThreadStart start = new ThreadStart(Start); array[i] = new Thread(start); array[i].Start(); } // Join all the threads. for (int i = 0; i < array.Length; i++) { array[i].Join(); } Console.WriteLine("DONE"); } static void Start() { // This method has no formal parameters. Console.WriteLine("Start()"); } }Start() Start() Start() Start() DONE
ParameterizedThreadStart
This starts a thread with a target method. We can then pass this instance to the Thread constructor. The target method is then invoked upon starting the Thread.
ParameterizedThreadStarts
, then start and join 4 threads. Start()
is executed 4 different times on separate threads.ParameterizedThreadStart
, you pass a function name as the argument. This is an object type that you can later cast.using System; using System.Threading; class Program { static void Main() { // Create an array of Thread references. Thread[] array = new Thread[4]; for (int i = 0; i < array.Length; i++) { // Start the thread with a ParameterizedThreadStart. ParameterizedThreadStart start = new ParameterizedThreadStart(Start); array[i] = new Thread(start); array[i].Start(i); } // Join all the threads. for (int i = 0; i < array.Length; i++) { array[i].Join(); } Console.WriteLine("DONE"); } static void Start(object info) { // This receives the value passed into the Thread.Start method. int value = (int)info; Console.WriteLine(value); } }1 0 2 3 DONE
What if you want to start a thread but don't need to pass any parameters to it? You don't need to pass the null
literal.
ThreadStart
type, which (fortunately) is detailed also on this page.ThreadStart
enables you to start a thread and pass no arguments to the target method. For parameterless target methods, this type is ideal.
ParameterizedThreadStart
gives you the ability to pass an argument of any type to a specific method on a thread. We can process many different data values on different threads.