C# Threading – Thread Class Constructors

The Thread class contains four constructors defined for specific purposes. You can checkout this by placing the cursor on Thread class and press 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);


Lets understand ThreadStart and ParamaterizedThreadStart delegates in detail:

Constructor 1: Constructor with ThreadStart deligate:

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: Constructor with ParametarizedThreadStart deligate:

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 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 specific data type.



– Article ends here –

If you have any questions, please feel free to share your questions or comments on the comment box below.

Recommended:   Simulating Blue Screen Of Death - BOSD error in C#
Share this:
We will be happy to hear your thoughts

Leave a reply

Troubleshootyourself
Logo