Multithreading In C# .NET

Introduction

If you have a program which executes from top to bottom, it would not be responsive and feasible to build complex Applications. Thus, .NET framework offers some classes to create complex Applications.

What is threading?

In short, thread is like a virtualized CPU, which helps to develop complex Applications.

Understanding threading

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

Thus, for this purpose, we will be using multithreading in C#.NET. Thus, we will divide our program into the different parts, using threading. You know, every Application runs its own process in Windows. Thus, 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 programs like property, status etc. of your thread.

Example

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

  1. class Program  
  2.     {  
  3.         private static void loopTask()  
  4.         {  
  5.             for(int x = 0; x<10; x++)  
  6.             {  
  7.                 Console.WriteLine("X => {0}", x);  
  8.                 Thread.Sleep(1000);  
  9.             }  
  10.         }  
  11.   
  12.         static void Main(string[] args)  
  13.         {  
  14.             ThreadStart thread = new ThreadStart(loopTask);  
  15.             Thread myThread = new Thread(thread);  
  16.               
  17.             myThread.Start();  
  18.   
  19.             for (int y = 0; y < 4; y++)  
  20.             {  
  21.                 Console.WriteLine("Main thread.");  
  22.                 Thread.Sleep(1000);  
  23.             }  
  24.   
  25.             Console.ReadKey();  
  26.         }  
Explanation:

You may observe this. I create a new Local Variable thread of ThreadStart delegate and pass the loopTask as a parameter to execute it. This loopTask function has a loop. We create a new object myThread from Thread Class and pass Local Variable thread to the Thread Constructor. Start the thread, using myThread.Start(); and Thread.Sleep(2000); will pause the current for 2000 milliseconds.

Finally, the result will be:

result

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

  1. class Program  
  2.     {  
  3.         static void Main(string[] args)  
  4.         {  
  5.             new Thread(new ThreadStart(() => {  
  6.                 for (int x = 0; x < 10; x++)  
  7.                 {  
  8.                     Console.WriteLine("X => {0}", x);  
  9.                     Thread.Sleep(1000);  
  10.                 }  
  11.             })).Start();  
  12.   
  13.             Console.ReadKey();  
  14.         }  
  15.     }  

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

Passing Value as Parameter

The Thread constructor has another overload, which 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.

  1. class Program  
  2.     {  
  3.         private static void loopTask(object value)  
  4.         {  
  5.             for(int x = 0; x<10; x++)  
  6.             {  
  7.                 Console.WriteLine("X => {0} And Parameter Value is => {1}", x, value);  
  8.                 Thread.Sleep(1000);  
  9.             }  
  10.         }  
  11.   
  12.         static void Main(string[] args)  
  13.         {  
  14.             Thread myThread = new Thread( new ParameterizedThreadStart(loopTask));  
  15.               
  16.             myThread.Start("Kashif");  
  17.   
  18.             Console.ReadKey();  
  19.         }  
  20.     }  

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

How to stop/abort a thread?

To stop the thread, what we use is Thread.Abort method. This method can be executed by other threads at any time. When Thread.Abort is executed, it throws an exception ThreadAbortException.

Example
  1. class Program  
  2.     {  
  3.         private static void loopTask()  
  4.         {  
  5.             try  
  6.             {  
  7.                 for (int i = 0; i < 10; i++)  
  8.                 {  
  9.                     Console.WriteLine(i);  
  10.                     Thread.Sleep(1000);  
  11.                 }  
  12.             }  
  13.             catch (ThreadAbortException e)  
  14.             {  
  15.                 Console.WriteLine(e.Message);  
  16.             }              
  17.         }  
  18.         static void Main(string[] args)  
  19.         {  
  20.             Thread t = new Thread(new ThreadStart(loopTask));  
  21.             t.Start();  
  22.             Thread.Sleep(2000);  
  23.             t.Abort();  
  24.             Console.ReadKey();  
  25.   
  26.         }  
  27.     }  
Thanks for reading. :)