Skip to main content

Threading In C#

Threading is very useful, when we are doing a multitask in a program. It will improve the application performance if we use 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 into 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:

public class PrintNumber  
       {  
           public void Print()  
           {  
               for (long i = 1; i <= 100; i++)  
               {  
                   Console.WriteLine(i);  
               }  
           }  
       }

 

Now, write the code, given below, inside the Main method.

static void Main(string[] args)  
        {  
            PrintNumber printNumber = new PrintNumber();  
            Thread t1 = new Thread(printNumber.Print);  
            Thread t2 = new Thread(printNumber.Print);  
            t1.Start();  
            t2.Start();  
            Console.ReadKey();  
        }

 

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.

Leave a Reply