Threading In C#

Threading is very useful, when we are doing a multitask in a program. It will improve the application performance, if we us it in the proper way. Generally, we are writing the programs where a single thread runs in a process at a time. However, in this way, the Application uses one thread to perform the multiple jobs in a processor.

To execute more than one task at a time, it can be divided into smaller threads and we can feel it as a concurrent programming in a processor. For example, a process can run one thread at a time and after some fraction of time the next thread will come and run,  the first thread will go in to the waiting state, while the next thread is running and wait for its time.

In this way, we can feel that a multitask is happening concurrently in a process, but actually the thread is running one after another in a very short interval of time. Threads are known as lightweight processes.

The following states in the life cycle of a thread are:

  • Unstarted State: When the instance of the thread is created but the Start method is not called.

  • Ready State: When the thread is ready to run and waits for CPU cycle.
Not Runnable State: When thread is in the condition, given below:
  • Sleep method has been called.
  • Wait method has been called.
  • Blocked by I/O operations.

The Dead State: When the thread is in the condition, given below:

  • Completes execution.
  • Aborted.

Here, we are going to create one sample Application to show how multi-thread is working in an Application.

First of all open Visual Studio, Go to File -> New - > Project -> choose as a console Application and enter the name of a project - “ThreadSample”, shown below in the image. 

Project

Create another class PrintNumber inside the Program class, shown below:

  1. public class PrintNumber  
  2.        {  
  3.            public void Print()  
  4.            {  
  5.                for (long i = 1; i <= 100; i++)  
  6.                {  
  7.                    Console.WriteLine(i);  
  8.                }  
  9.            }  
  10.        }  
Now, write the code, given below, inside the Main method.
  1. static void Main(string[] args)  
  2.         {  
  3.             PrintNumber printNumber = new PrintNumber();  
  4.             Thread t1 = new Thread(printNumber.Print);  
  5.             Thread t2 = new Thread(printNumber.Print);  
  6.             t1.Start();  
  7.             t2.Start();  
  8.             Console.ReadKey();  
  9.         }  
Now, run the Application and see the output, shown below:

application

Here, in the example, shown above, we can clearly see the output, where the first thread and second thread are running independently.

I will focus on more scenarios in my next article.