Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • C# Data Types
  • C# Decision Making
  • C# Methods
  • C# Delegates
  • C# Constructors
  • C# Arrays
  • C# ArrayList
  • C# String
  • C# Tuple
  • C# Indexers
  • C# Interface
  • C# Multithreading
  • C# Exception
Open In App
Next Article:
C# Multithreading
Next article icon

C# Multithreading

Last Updated : 03 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

C# is a multi-paradigm programming language that supports several programming styles, including procedural, object-oriented, and functional programming. One of the essential features of C# is its support for multithreading, which enables developers to write applications that can perform multiple tasks concurrently.

Multithreading in C# is a programming technique that allows multiple threads to run concurrently within a single process. Each thread represents a separate execution path, enabling tasks to be performed in parallel, improving the efficiency and performance of applications.

Example: Implementation of multithreading using Thread class.

C#
// Creating a thread using the Thread class in C# using System; using System.Threading;  class Geeks { 	static void Main() 	{ 		// create a new thread 		Thread t = new Thread(Worker);  		// start the thread 		t.Start();  		// do some other work in the main thread 		for (int i = 1; i < 5; i++) 		{ 			Console.WriteLine("Main thread doing some work"); 			Thread.Sleep(100); 		}  		// wait for the worker thread to complete 		t.Join();  		Console.WriteLine("Done"); 	}  	static void Worker() 	{ 		for (int i = 1; i < 3; i++) 		{ 			Console.WriteLine("Worker thread doing some work"); 			Thread.Sleep(100); 		} 	} } 

Output
Worker thread doing some work Main thread doing some work Worker thread doing some work Main thread doing some work Main thread doing some work Main thread doing some work Done 

Explanation: In the above example, we create and start a new thread that runs the Worker method while the main thread performs its task. Both threads print messages and sleep for a short duration. The main thread waits for the worker thread to complete before printing "Done".

Real-World Example

Multitasking is the simultaneous execution of multiple tasks or processes over a certain time interval. Windows operating system is an example of multitasking because it is capable of running more than one process at a time like running Google Chrome, Notepad, VLC player, etc. at the same time. The operating system uses a term known as a process to execute all these applications at the same time.

  • Process: A Process is a part of an operating system that is responsible for executing an application.
  • Thread: A thread is a lightweight process, or in other words, a thread is a unit which executes the code under the program.

Every program has logic and a thread is responsible for executing this logic. Every program by default carries one thread to execute the logic of the program and the thread is known as the Main Thread, so every program or application is by default single-threaded model.

Single Threaded Model

The single thread runs all the processes present in the program in a synchronizing manner, which means one after another. So, the second process waits until the first process completes its execution, it consumes more time in processing. For example, we have a class named Geek and this class contains two different methods, i.e. method1, and method2. Now the main thread is responsible for executing all these methods, so the main thread executes all these methods one by one.

SingleThreadedModel


Example: Illustration of Single-Threaded Model

C#
// Single threaded model example using System; using System.Threading;  public class Geek {     public static void method1()     {         // It prints numbers from 0 to 4         for (int i = 1; i < 5; i++)         {              Console.WriteLine("Method1 is : {0}", i);              if (i == 2)             {                 Thread.Sleep(100);             }         }     }     public static void method2()     {         // It prints numbers from 0 to 4         for (int j = 1; j < 5; j++)         {              Console.WriteLine("Method2 is : {0}", j);         }     } }  public class Geeks {     static public void Main()     {          // Calling static methods         Geek.method1();         Geek.method2();     } } 

Output
Method1 is : 1 Method1 is : 2 Method1 is : 3 Method1 is : 4 Method2 is : 1 Method2 is : 2 Method2 is : 3 Method2 is : 4 

Explanation: In the above example method 2 is waiting for method 1 until it is completed it will not work this is the drawback of a single-threaded model here to overcome this multithreading comes where we can run different programs and different threads simultaneously. Also maximizing the utilization of the CPU because multithreading works on a time-sharing concept means each thread takes its own time for execution and does not affect the execution of another thread, this time interval is given by the operating system.\

Multithreading allows the program to run multiple threads concurrently. It can significantly improve performance and responsiveness in applications.

file

Example: Illustration of Multithreading in C#

C#
// C# program to illustrate the // concept of multithreading using System; using System.Threading;  public class Geeks {     public static void method1()     {          for (int i = 1; i < 5; i++)         {             Console.WriteLine("Method1 is : {0}", i);              // sleep for 100 milliseconds             if (i == 2)             {                 Thread.Sleep(100);             }         }     }      public static void method2()     {         // It prints numbers from 0 to 10         for (int j = 1; j < 5; j++)         {             Console.WriteLine("Method2 is : {0}", j);         }     }     static public void Main()     {         // Creating and initializing threads         Thread thr1 = new Thread(method1);         Thread thr2 = new Thread(method2);         thr1.Start();         thr2.Start();     } } 

Output
Method1 is : 1 Method1 is : 2 Method2 is : 1 Method2 is : 2 Method2 is : 3 Method2 is : 4 Method1 is : 3 Method1 is : 4 

Explanation: In the above example, we create and initialize two threads, i.e. thr1 and thr2 using the Thread class. Now using thr1.Start(); and thr2.Start(); we start the execution of both threads. Now both thread runs simultaneously and the processing of thr2 does not depend upon the processing of thr1 like in the single-threaded model.

Note: Output may vary due to context-switching

Ways to Implement Multithreading

In C#, multithreading is supported through the System. Threading namespace. There are several ways to create and manage threads described below:

  1. Thread Class
  2. Task Class
  3. Async and Await
  4. ThreadPool Class

1. Thread Class

The Thread class is the most basic way to implement multithreading in C#. We can create a thread by instantiating a Thread object and passing a method that represents the task to be executed.

Example: Creating threads using the Thread class.

C#
// Implementing Multithreading using Thread class using System; using System.Threading;  class Geeks {     static void Main()     {         Thread thread1 = new Thread(PrintNumbers);                  // Start the thread         thread1.Start();          PrintNumbers();     }      static void PrintNumbers()     {         for (int i = 1; i < 5; i++)         {             Console.WriteLine(i);             Thread.Sleep(100);         }     } } 

Output
1 1 2 2 3 3 4 4 

Explanation: In the above example, the PrintNumbers method runs in both the main thread and a separate thread1. The Start() method initiates the execution of the thread. Simulates some work by making the thread pause for a few seconds between iterations.

2. Task Class

Task class used for more complex or parallel tasks also known as Task Parallel Library (TPL). The Task class allows us to create tasks that can run asynchronously, improving both performance and code readability. It also simplifies task management by handling thread pooling and synchronization.

Example:

C#
// Implmentation of Multithreading in C# using Task Class using System; using System.Threading.Tasks;  class Geeks {     static void Main()     {         // Running two tasks concurrently         Task task1 = Task.Run(() => PrintNumbers());         Task task2 = Task.Run(() => PrintNumbers());          // Wait for both tasks to complete         Task.WhenAll(task1, task2).Wait();     }      static void PrintNumbers()     {         for (int i = 0; i < 3; i++)         {             Console.WriteLine(i);         }     } } 

Output
0 1 2 0 1 2 

Explanation: In the above example, two tasks are created using Task.Run(). These tasks execute the PrintNumbers method concurrently, improving overall performance. The Task.WhenAll() method ensures that both tasks are complete before the program finishes execution.

3. Async and Await

There is another way to perform multitasking we can use asynchronous tasks using the keyword async and await which are used for asynchronous programming, they can combine CPU-bound and I/O-bound operations. It is not a traditional multithreading, can be combined with a Task.Run for non-blocking multithreaded operations.

Example: Demonstratrating use of Async and Await in multithreaded environment.

C#
// Combining tasks with async/await to perform  // asynchronous operations using System; using System.Threading; using System.Threading.Tasks;  class Geeks {     static void Main()     {         // Example using Threads         Thread thread1 = new Thread(() => task("Thread 1"));         Thread thread2 = new Thread(() => task("Thread 2"));         thread1.Start();         thread2.Start();         thread1.Join();         thread2.Join();          Console.WriteLine("moving to task");          // Example using Tasks with async/await         Task.Run(async () => await RunAsyncTasks()).Wait();          Console.WriteLine("All tasks completed.");     }      static void task(string threadName)     {         for (int i = 1; i <= 2; i++)         {             Console.WriteLine($"{threadName} print: {i}");             Thread.Sleep(100); // Simulate work         }     }      static async Task RunAsyncTasks()     {         Task task1 = Task.Run(() => task("Task 1"));         Task task2 = Task.Run(() => task("Task 2"));          await Task.WhenAll(task1, task2);     } } 

Output
Thread 1 print: 1 Thread 2 print: 1 Thread 1 print: 2 Thread 2 print: 2 moving to task Task 1 print: 1 Task 2 print: 1 Task 1 print: 2 Task 2 print: 2 All tasks completed. 


4. ThreadPool Class

ThreadPool class is a useful feature of C#. Which manages a pool of threads and can be used to execute tasks asynchronously and manages a pool of threads and can be used to execute tasks asynchronously. So Instead of creating and destroying threads for every task, which can be resource-intensive, the ThreadPool allows multiple tasks to share a limited number of threads. This leads to reduced overhead and improved performance, especially in applications that require frequent short-lived operations.

Example: Demonstration of ThreadPool Class in C#

C#
// Use of ThreadPool Class using System; using System.Threading;  class Geeks {     static void Main()     {         // queue a work item to the thread pool         ThreadPool.QueueUserWorkItem(Worker, "Hello, world!");          // do some other work in the main thread         for (int i = 1; i < 5; i++)         {             Console.WriteLine("Main thread doing some work");             Thread.Sleep(100);         }          Console.WriteLine("Done");     }      static void Worker(object state)     {         string message = (string)state;          for (int i = 1; i < 5; i++)         {             Console.WriteLine(message);             Thread.Sleep(100);         }     } } 

Output
Main thread doing some work Hello, world! Hello, world! Main thread doing some work Main thread doing some work Hello, world! Hello, world! Main thread doing some work Done 

Explanation: In this example, the Worker method is executed in a separate thread while the main thread is doing some other work. The Thread.sleep method is used to simulate some work being done in both threads.

Important Points:

  • Deadlocks: Ensure that threads do not get stuck waiting for resources held by each other. Use lock carefully and try to lock resources in a consistent order.
  • Thread Pooling: Use Task.Run() and the ThreadPool to avoid manually managing threads. Thread pooling reduces overhead and ensures efficient resource utilization.
  • Time-Limit: Always provide a mechanism for cancelling long-running tasks to improve responsiveness, especially in UI applications.
  • Shared Data: Minimize the use of shared data between threads to avoid race conditions. If shared data is necessary, ensure proper synchronization.

Advantages

  • It executes multiple processes simultaneously.
  • Maximize the utilization of CPU resources.
  • Time sharing between multiple processes.
  • Help to achieve Multitasking.

Next Article
C# Multithreading

A

ankita_saini
Improve
Article Tags :
  • C#
  • CSharp Multithreading

Similar Reads

    C# Main Thread
    In C#, threads are the smallest units of execution that allow parallel execution of code, enabling multiple tasks to run concurrently within a single process. The Thread class in the System.Threading namespace is used to create and manage threads. In C#, the Main method is the entry point of any con
    5 min read
    C# Thread Class
    In C#, multi-threading is implemented using the Thread class, which is part of the System.Threading namespace. This class allows for the creation, management, and control of threads within an application. The Thread class provides various methods and properties to handle thread execution, prioritize
    7 min read
    How to Create Threads in C#?
    Multithreading enables concurrent task execution in C#. It improves performance and responsiveness. We can create threads using the System.Threading namespace. With the help of Threads, we can achieve multitasking and can define their behavior using different methods provided by the Thread Class. Ex
    6 min read
    C# Types of Threads
    Multithreading is one of the core features in C# that allows multiple tasks to be performed concurrently. Threads allow your application to run multiple tasks simultaneously, improving performance, and resource utilization. In C#, there are two types of threads.Foreground ThreadsBackground ThreadsNo
    4 min read
    Multithreading in C
    A thread is a single sequence stream within a process. Because threads have some of the properties of processes, they are sometimes called lightweight processes. But unlike processes, threads are not independent from each other unlike processes. They share with other threads their code section, data
    9 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences