
C# Threading – Thread Class Constructors
The Thread class contains four constructors defined for specific purposes. You can check out this by placing the cursor on Thread class and pressing F12, this will take you to the Thread Class meta file and there you can see Thread constructors as listed below.
public Thread(ParameterizedThreadStart start);
public Thread(ThreadStart start);
public Thread(ParameterizedThreadStart start, int maxStackSize);
public Thread(ThreadStart start, int maxStackSize);
Let’s understand ThreadStart and ParamaterizedThreadStart delegates in detail:
Constructor 1: Constructors with ThreadStart delegate:
public Thread(ParameterizedThreadStart start);
The constructor initializes a new instance of the System.Threading.Thread class. A ThreadStart is a delegate that represents the methods to be invoked when this thread begins executing.
Example:
You can also create the Thread by combining the above two steps as below;
Thread t1 = new Thread(new ThreadStart(DisplayCount1);
t1.Start();
You can write altogether in one line code as below.
Thread t1 = new Thread(new ThreadStart(DisplayCount1).Start();
Constructor 2: Constructors with ParametarizedThreadStart delegate:
public Thread(ParameterizedThreadStart start);
The constructor Initializes a new instance of the System.Threading.Thread class by specifying a delegate that allows an object to be passed to the thread when the thread is started.
Example:
You can also create the Thread by combining the above two steps as below;
Thread t1 = new Thread(new ParametarizedThreadStart(DisplayCount1);
t1.Start(3);
You can write altogether in one line code as below.
Thread t1 = new Thread(new ParametarizedThreadStart(DisplayCount1).Start(3);
The parameter type of ParametarizedThreadStart delegate is an object type and hence it is not type-safe. In this case, the thread function should have conversion logic where the object type is converted and assigned to a specific data type.
– Article ends here –
Read more from the Microsoft published article here.