Table of contents
1.
Introduction
2.
Life Cycle of Thread
3.
The Thread Class
3.1.
Constructors in Thread Class
3.2.
Properties in Thread Class
3.3.
Methods in Thread Class
3.4.
Create a Thread
3.5.
The Main Thread
3.6.
Check status of Current Thread
3.7.
Get the name of Current Thread
3.8.
Display the priority of the Current Thread
3.9.
Pause the Thread for a specified period
4.
Frequently Asked Questions
4.1.
What are the challenges for multithreading C#?
4.2.
Why do we need multithreading in C#?
4.3.
Does C# support multiple threads?
4.4.
How many types of threads are there in C#?
5.
Conclusion
Last Updated: Mar 27, 2024
Medium

Multithreading in Csharp

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Ms word: You're using MS Word to write a paragraph. However, another process is operating in the background, verifying your spelling problems. When you make a typo, the other process tells you of the error. And it simplifies your life. To run all of these processes at the same time, the operating system employs a concept known as a process. A process is an operating system component that is in charge of executing an application. Every software that runs on your system is a process, and processes employ a phrase called a thread to run the code inside the application.

multithreading in c#

The execution path of a program is defined as a thread. Each thread defines a distinct control flow. If your application has a requirement of complex and time-consuming tasks, it is better to have multiple execution routes or threads, each of which performs a certain task.

Threads are a lightweight method of production. The implementation of concurrent programming by modern operating systems is a common example of thread utilization. The use of threads reduces CPU cycle waste and improves application efficiency.

Life Cycle of Thread

The life cycle of a thread can be defined as the state transitions of a thread that starts from its birth till it ends. Thread has a very important role in Multithreading In C# (Also see, Introduction to C#). There are several life cycles in which a thread lies at any instant.

Life Cycle of Thread

When we use the Thread class to create a new Thread object, it starts its life cycle in the new state. A newborn State is a state in which a thread is born. This remains in this state until the Thread is started by the program. You can call the thread using the start() method; otherwise, it might throw an error.

The thread proceeded from the New state to a runnable state as soon as the start() method was called. A thread has joined the queue of threads waiting to be executed in this state.

Waiting: When a thread is in waiting mode, it awaits the completion of another thread's task.

Timed Waiting: A thread can transfer its timed waiting state to another thread so that it can complete its task.

When the run() method completes its execution, the thread becomes terminated(Dead). When the halt() method is called, a thread method can also be completed.

When a thread is considered blocked, it is suspended, sleeping, or waiting for a short period of time to confirm certain conditions.

The Thread Class

A thread is a lightweight process which runs alongside other threads using shared memory. The Thread class in C# represents an execution thread, and the Thread class is a system class. It provides methods to start, stop, and join threads as well as manage thread priorities and scheduling.

Constructors in Thread Class

Here is the table that explains the constructors in the thread class

Constructor Description
Thread() Creates a new thread with the default priority and name.
Thread(ThreadStart start) Creates a new thread that executes the specified delegate.
Thread(ParameterizedThreadStart start, object state) Creates a new thread that executes the specified delegate with the specified state.

Properties in Thread Class

Property Description
CurrentThread It shows an instance of the currently running thread.
Name It is used to set the name of current thread
IsAlive Check whether the thread is alive or not
Priority It is used to set the priority of the thread
IsBackground Used to check whether the current thread is running in the background or not.
ThreadState It returns the value of the current thread

Methods in Thread Class

Methods Description
Abort() It is used for the termination of Multithreading In C#
Join() It is used for blocking all the calling threads until this thread terminates
Resume() It is used when we want to resume the suspended thread
start() It changes the state of thread to runnable
Interrupt() It is used to interrupt the thread

Create a Thread

The threads are created by extending the Thread class and overriding the Run() method. Then write the code you want to execute in the run() method and after that create an instance of the class and call the Start() method.

Let's see an example to demonstrate the concept:

using System;
using System.Threading;
namespace ThreadCreationApplication
{
   class ThreadCreationProgram
   {
       static void Main(string[] args)
       {
           // Create a new thread object.
           Thread childThread = new Thread(() =>
           {
               // This is the code that will be executed by the child thread.
               Console.WriteLine("Child thread is running");
           });
           // Start the child thread.
           childThread.Start();
           // Wait for the child thread to finish.
           childThread.Join();
           Console.WriteLine("Child thread finished");
       }
   }
}

Output

In Main: Creating the Child thread
Child thread is running
Child thread finished

The Main Thread

The System.Threading.Thread class is responsible for working with threads. A multithreaded program allows you to create and access individual threads. The main thread is the first thread to be executed in a process. The main thread is automatically established when a C# application begins to run. The threads produced with the Thread class are referred to as the primary thread's child threads. The Thread class's CurrentThread property can be used to access a thread. Let's see the example of Multithreading In C#.

// Multithreading In C#
using System;
using System.Threading;
// Multithreading In C#
namespace MultithreadingApplication {
   class MainThreadExecution {
      static void Main(string[] args) {
         Thread threadDummy = Thread.CurrentThread;
         threadDummy.Name = "This is main thread";
         
         Console.WriteLine( threadDummy.Name);
   
      }
   }
}

Output 

This is main thread

Check status of Current Thread

In order to check the status of the current Thread, we can use Thread.state property. The thread.state returns the current state of the thread. The possible states are:

  • New: The thread has not started 
     
  • Runnable: The thread is ready to run
     
  • Blocked: The thread is waiting for a resource 
     
  • Waiting: The thread is waiting for another thread to perform an action
     
  • Timed_Waiting: The thread is waiting  to perform an action for the specific time period
     
  • Terminated: The thread has finished executing
     

Let's see the code snippet used for checking the status in C#.

using System;
using System.Threading;
namespace CheckThreadStatus
{
   class Program
   {
       static void Main(string[] args)
       {
           // Check the status of the current thread.
           Thread.State state = Thread.CurrentThread.State;
           Console.WriteLine("Current thread state: {0}", state);  
       }
   }
}

Output

Current thread state: Running

Get the name of Current Thread

In order to get the name of the current thread we have a Thread.name property that returns the name of the current thread. If there is no thread created the property will return an empty string.

Let's see the code snippet used to get the name of the current thread in C#.

using System;
using System.Threading;
namespace CheckThreadStatus
{
   class Program
   {
       static void Main(string[] args)
       {
           // Get the name of the current thread.
           string name = Thread.CurrentThread.Name;
           Console.WriteLine("Current thread name: {0}", name);
          
       }
   }
}

Output

Current thread name: Main

Display the priority of the Current Thread

In order to display the priority of the current thread then we have a property called Thread.priority that returns the priority of the current thread. The priority is a value between 1 and 10. The higher the priority of a thread the more important it would be.

Let's see the code snippet used to get the priority of the current thread in C#.

using System;
using System.Threading;
namespace CheckThreadStatus
{
   class Program
   {
       static void Main(string[] args)
       {
            // Display the priority of the current thread.
           int priority = Thread.CurrentThread.Priority;
           Console.WriteLine("Current thread priority: {0}", priority);
          
       }
   }
}

Output

Current thread priority: 3

Pause the Thread for a specified period

To pause a thread we can use Thread.sleep() method. This method takes two arguments: the number of milliseconds to sleep for, and the number of nanoseconds to sleep for. The thread.sleep() method will put the thread in sleeping mode till the time gets over and then the thread will wake and start executing.

Let's see the code snippet on how to pause the thread in C#.

using System;
using System.Threading;

namespace SleepThread
{
    public class Program
    {
        public static void Main(string[] args)
        {
            // Create a new thread
            Thread thread = new Thread(() =>
            {
                Console.WriteLine("Thread started");

                // Sleep for 2 seconds
                Thread.Sleep(2000);

                Console.WriteLine("Thread woke up");
            });

            // Start the thread
            thread.Start();
        }
    }
}

Output

Thread started
--- After 2 second of sleep ------
Thread woke up

 

Must Read IEnumerable vs IQueryable.

Frequently Asked Questions

What are the challenges for multithreading C#?

The challenge for multithreading in c# is that it is difficult to keep track of shared resources and prevent race conditions. Performance issues are also there due to multiple threads competing for CPU time.

Why do we need multithreading in C#?

Multithreading in C# is the concept of running multiple threads simultaneously which enhances the performance of the application and gets the work done faster by utilizing the CPU.

Does C# support multiple threads?

C# support multiple threads and in order to create new threads we can take the help of the Thread class. Multiple Threading enhances the performance of the application.

How many types of threads are there in C#?

In C#, there are mainly two types of threads: Foreground and Background threads. Foreground threads keep the application running until they complete, while Background threads do not prevent the application from terminating and are stopped when all Foreground threads have finished.

Conclusion

In this article, we have extensively discussed Multithreading In C#. We have discussed a lot of theories on threading along with code examples of Multithreading in C#. 

Recommended Readings:

 

Do check out The Interview guide for Product Based Companies as well as some of the Popular Interview Problems from Top companies like Amazon, Adobe, Google, etc. on Coding Ninjas Studio.

Also check out some of the Guided Paths on topics such as Data Structure and Algorithms, Competitive Programming, Operating Systems, etc. as well as some Contests, Test Series, Interview Bundles, and some Interview Experiences curated by top Industry Experts only on Coding Ninjas Studio.

Live masterclass