C# Threading – Thread Class Constructors


The Thread class contains four constructors defined for specific purpose. 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.

Lets understand ThreadStart and ParamaterizedThreadStart delegates in detail:

Constructor 1: Constructor with ThreadStart deligate:

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.

Recommended:   Visual Studio IDE Shortcut Keys
Example:

You can also create the Thread by combining the above two steps as below;

You can write altogether in one line code as below.

Constructor 2: Constructor with ParametarizedThreadStart deligate:

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;

Recommended:   Tuples in C# - Return more than one value from Method

You can write altogether in one line code as below.

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 converted and assigned to specific datatype.

Share this:

We will be happy to hear your thoughts

Leave a reply