Learn Multithreading In C# .Net

If you have a program that executes from top to bottom, it will not be responsive and feasible to build complex applications. So, the .NET Framework offers some classes to create complex applications.

What is threading?

In short, thread is like a virtualized CPU which will help to develop complex applications.

Understanding threading

Suppose, you have a computer which only has one CPU capable of executing only one operation at a time. And, your application has a complex operation. So, in this situation, your application will take too much time. This means that the whole machine will freeze and appear unresponsive. So your application performance will decrease.

For protecting the performance, we will be multithreading in C#.NET. So, we will divide our program into different parts using threading. And you know every application run its own process in Windows. So every process will run in its own thread.

Thread Class

Thread class can be found in System.Threading namespace, using this class you can create a new thread and can manage your program like property, status etc. of your thread.

Example

The following code shows how to create thread in C#.NET

Explanation

You may observe that, I created a new Local Variable thread of ThreadStart delegate and pass loopTaskas a parameter to execute it. This loopTask Function has a loop. And we create a new object myThreadfrom Thread Class and pass Local Variable thread to Thread Constructor. And start the Thread using myThread.Start(); and Thread.Sleep(2000); will pause for 2000 milliseconds.

And finally the result will be

test1

This code also can be written in a more simple way like this.

In the above code, we are using lambda expression ( => ) for initialization.

Passing Value as Parameter

The Thread constructor has another overload that takes an instance of a ParameterizedThreadStart delegate. It can be used if you want to pass some data through the start method of your thread to your method,

In this case, the value is passed to the loopTask as an object. You can cast it to the expected type.

hflbnner