Thread class in .NET

System.Thread is the simplest and in the same time the most widely used class for Task Parallelism in DOT NET. In this article we will explain several important methods, attributes and ways to use System.Thread efficiently.

We will take several cases and properties of Thread.Sleep and explore it’s effect and how can we make use of it in our applications. Thread sleep’s task is stops the execution for specific interval.

The following application, will shows us how the main thread running in the main will make switches with the other thread so we can see the strings printed by both threads interchangeably :

IsBackground property means that the thread will work in the background and it could be terminated if the foreground threads finished or closed.

By adding the property (IsBackground) and the main thread, and increasing the thread sleep interval inside the thread method, we can see that it will closes directly if the property (IsBackground) was set to the thread object; and if we keep it as default (false), then the application will print the output of each iteration in the thread until it finish and then the window will close:

What if we needed to pass some parameter to the thread?

Simply we can use ParameterizedThreadStart instead of ThreadStart class. But passing parameters to the thread should always be as an object, not by specific classes like integer or string. Parsing more than one parameter should be considered to be within the same object, no multiple parameters are allowed in the ParameterizedThreadStart, but it could be easily done by passing an object of a class that contains all the needed parameters by lambda expression or by passing an object:

Or by lambda expression:

Thread join

Let’s have a look to this code:

Now after each thread start we will get the result in the next step, what will happen is that we will only get the result of a from t1, because b thread will not have the time to finish at the time when we’re summing a and b.

So without enabling the sleep we will get (9) which is the result of (a), but after adding sleep(1) in MethodA we will get 0, the same if we add a sleep in MethodB.

But after adding two joins for each thread we will get the correct result (25).

It could be noticed that I have used two static variables and there value was the same for all the threads. However if we want to have one copy for each thread from some variable we can use [ThreadStatic] attribute above the static variable declaration and it will be copied to each thread separately. Similar to [ThreadStatic] there’s a ThreadLocal<T> which is represented by a list of (T) that can hold information per each thread.