C# ParameterizedThreadStart Program

This C# example program uses ParameterizedThreadStart. It implements important threading functionality.

ParameterizedThreadStart starts a thread with an argument.

It is instantiated with a target method. We can then pass this instance to the Thread constructor. The target method is then invoked upon starting the Thread.

 

 

Example. As an overview, this program creates an array of four threads, creates ParameterizedThreadStarts for them, then starts them and joins them. The static Start method is executed four different times on separate threads.

 

Tip: With ParameterizedThreadStart, you pass a function name as the argument. This is an object type that you can later cast.

Based on:

.NET 4.5

C# program that uses ParameterizedThreadStart

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);
    }
}

Output

1
0
2
3
DONE

In this example, the threads were called in a non-sequential order. This is because there is some indeterminate pause before the OS and Framework can receive a thread, and by that time we may have already requested another thread.

Note: You can't count on the order of execution exactly here. A thread may take longer for reasons beyond your control.

 

No parameters. 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. You can instead use the ThreadStart type, which fortunately is detailed also on this site.

 

Note: Please visit the more specific article. If parameters are required, this is clearer.

ThreadStart

 

Summary. ParameterizedThreadStart gives you the ability to pass an argument of any type to a specific method on a thread. This functionality enables you to process many different data values on different threads, improving performance and runtime.

Thread Join