The Wayback Machine - https://web.archive.org/web/20240910113832/https://www.geeksforgeeks.org/c-sharp-multithreading/
Open In App

C# Multithreading

Last Updated : 22 Feb, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

To create a new thread in C#, you can use the Thread class. Here’s an example of how to create a new thread and start it:

C#




using System;
using System.Threading;
 
class Program
{
    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 = 0; i < 10; 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 = 0; i < 10; i++)
        {
            Console.WriteLine("Worker thread doing some work");
            Thread.Sleep(100);
        }
    }
}


Output

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

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.

Another useful feature of C# is the ThreadPool class, which manages a pool of threads and can be used to execute tasks asynchronously. Here’s an example of how to use the ThreadPool class:

C#




using System;
using System.Threading;
 
class Program
{
    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 = 0; i < 10; 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 = 0; i < 10; i++)
        {
            Console.WriteLine(message);
            Thread.Sleep(100);
        }
    }
}


Output

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

In this example, the Worker method is executed in a thread from the thread pool while the main thread is doing some other work. The ThreadPool.QueueUserWorkItem method is used to queue the work item to the thread pool. The state object can be used to pass data to the worker method.

These are just a couple of examples of how to use multithreading in C#. There are many other techniques and tools available to help you write efficient and scalable multithreaded applications.

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. A process is a part of an operating system that is responsible for executing an application. Every program that executes on your system is a process and to run the code inside the application a process uses a term known as a thread. A thread is a lightweight process, or in other words, a thread is a unit which executes the code under the program. So every program has logic and a thread is responsible for executing this logic. Every program by default carries one thread to executes 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. This single-threaded model has a drawback. The single thread runs all the process present in the program in synchronizing manner, 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 as Geek and this class contains two different methods, i.e method1, method2. Now the main thread is responsible for executing all these methods, so the main thread executes all these methods one by one. Example: 

CSharp




// C# program to illustrate the
// concept of single threaded model
using System;
using System.Threading;
 
public class Geek {
 
    // static method one
    public static void method1()
    {
 
        // It prints numbers from 0 to 10
        for (int I = 0; I <= 10; I++) {
 
            Console.WriteLine("Method1 is : {0}", I);
 
            // When the value of I is equal to
            // 5 then this method sleeps for
            // 6 seconds and after 6 seconds
            // it resumes its working
            if (I == 5) {
                Thread.Sleep(6000);
            }
        }
    }
 
    // static method two
    public static void method2()
    {
 
        // It prints numbers from 0 to 10
        for (int J = 0; J <= 10; J++) {
 
            Console.WriteLine("Method2 is : {0}", J);
        }
    }
}
 
// Driver Class
public class GFG {
 
    // Main Method
    static public void Main()
    {
 
        // Calling static methods
        Geek.method1();
        Geek.method2();
    }
}


Output:

Method1 is : 0
Method1 is : 1
Method1 is : 2
Method1 is : 3
Method1 is : 4
Method1 is : 5
Method1 is : 6
Method1 is : 7
Method1 is : 8
Method1 is : 9
Method1 is : 10
Method2 is : 0
Method2 is : 1
Method2 is : 2
Method2 is : 3
Method2 is : 4
Method2 is : 5
Method2 is : 6
Method2 is : 7
Method2 is : 8
Method2 is : 9
Method2 is : 10

Explanation: Here, first of all, method1 executes. In method1 , for loop starts from 0 when the value of i is equal to 5 then the method goes into sleep for 6 seconds and after 6 seconds it resumes its process and print remaining value. Until method2 is in the waiting state. method2 start its working when method1 complete its assigned task. So to overcome the drawback of single threaded model multithreading is introduced. Multi-threading is a process that contains multiple threads within a single process. Here each thread performs different activities. For example, we have a class and this call contains two different methods, now using multithreading each method is executed by a separate thread. So the major advantage of multithreading is it works simultaneously, which means multiple tasks execute at the same time. And also maximizing the utilization of the CPU because multithreading works on time-sharing concept mean 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. Example: 

CSharp




// C# program to illustrate the
// concept of multithreading
using System;
using System.Threading;
 
public class GFG {
 
    // static method one
    public static void method1()
    {
 
        // It prints numbers from 0 to 10
        for (int I = 0; I <= 10; I++) {
            Console.WriteLine("Method1 is : {0}", I);
 
            // When the value of I is equal to 5 then
            // this method sleeps for 6 seconds
            if (I == 5) {
                Thread.Sleep(6000);
            }
        }
    }
 
    // static method two
    public static void method2()
    {
        // It prints numbers from 0 to 10
        for (int J = 0; J <= 10; J++) {
            Console.WriteLine("Method2 is : {0}", J);
        }
    }
 
    // Main Method
    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 : 0
Method1 is : 1
Method1 is : 2
Method1 is : 3
Method2 is : 0
Method2 is : 1
Method2 is : 2
Method2 is : 3
Method2 is : 4
Method2 is : 5
Method2 is : 6
Method2 is : 7
Method2 is : 8
Method2 is : 9
Method2 is : 10
Method1 is : 4
Method1 is : 5
Method1 is : 6
Method1 is : 7
Method1 is : 8
Method1 is : 9
Method1 is : 10

Explanation: Here, we create and initialize two threads, i.e thr1 and thr2 using Thread class. Now using thr1.Start(); and thr2.Start(); we start the execution of both the 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. Advantages of Multithreading:

  • It executes multiple process simultaneously.
  • Maximize the utilization of CPU resources.
  • Time sharing between multiple process.


Similar Reads

C# | Thread Priority in Multithreading
In a Multithreading environment, each thread has their own priority. A thread's priority shows how frequently a thread gains the access to CPU resources. Whenever we create a thread in C#, it always has some priority assigned to it. Important Points: A programmer can explicitly assign priority to a thread. The by default priority of a thread is Nor
3 min read
C# Tutorial
In this C# (C Sharp) tutorial, whether you’re beginner or have experience with other programming languages, our free C# tutorials covers the basic and advanced concepts of C# including fundamentals of C#, including syntax, data types, control structures, classes, and objects. You will also dive into more advanced topics like exception handling, and
8 min read
ASP.NET Interview Questions and Answer
ASP.NET is a powerful framework for building dynamic web applications, known for its scalability, performance, and integration with the .NET ecosystem, developed by Microsoft that allows developers to build dynamic web applications, websites, and services. It is part of the larger .NET framework and provides a comprehensive programming model for cr
15+ min read
C# Interview Questions and Answers
C# is the most popular general-purpose programming language and was developed by Microsoft in 2000, renowned for its robustness, flexibility, and extensive application range. It is simple and has an object-oriented programming concept that can be used for creating different types of applications. Here, we will provide 50+ C# Interview Questions and
15+ min read
Differences Between .NET Core and .NET Framework
.NET Core is a free open source, a general-purpose development platform for developing modern cloud-based software applications on Windows, Linux, and macOS operating systems. It operates across several platforms and has been revamped to make .NET fast, scalable, and modern. .NET Core is one of Microsoft's big contributions and released under the M
4 min read
Basic CRUD (Create, Read, Update, Delete) in ASP.NET MVC Using C# and Entity Framework
Prerequisites: Download and Install Microsoft SQL Server Management StudioDownload and Setting Up Visual Studio Community Version MVC stands for Model View Controller. It is a design pattern that is employed to separate the business logic, presentation logic, and data. Basically, it provides a pattern to style web application. As per MVC, you can d
6 min read
Program to calculate Electricity Bill
Given an integer U denoting the amount of KWh units of electricity consumed, the task is to calculate the electricity bill with the help of the below charges: 1 to 100 units - [Tex]Rs. 10/unit[/Tex]100 to 200 units - [Tex]Rs. 15/unit[/Tex]200 to 300 units - [Tex]Rs. 20/unit[/Tex]above 300 units - [Tex]Rs. 25/unit[/Tex] Examples: Input: U = 250 Outp
9 min read
Garbage Collection in C# | .NET Framework
Garbage collection is a memory management technique used in the .NET Framework and many other programming languages. In C#, the garbage collector is responsible for managing memory and automatically freeing up memory that is no longer being used by the application. The garbage collector works by periodically scanning the application's memory to det
8 min read
Linked List Implementation in C#
A LinkedList is a linear data structure which stores element in the non-contiguous location. The elements in a linked list are linked with each other using pointers. Or in other words, LinkedList consists of nodes where each node contains a data field and a reference(link) to the next node in the list. In C#, LinkedList is the generic type of colle
6 min read
HashSet in C# with Examples
In C#, HashSet is an unordered collection of unique elements. This collection is introduced in .NET 3.5. It supports the implementation of sets and uses the hash table for storage. This collection is of the generic type collection and it is defined under System.Collections.Generic namespace. It is generally used when we want to prevent duplicate el
6 min read
C# Dictionary with examples
In C#, Dictionary is a generic collection which is generally used to store key/value pairs. The working of Dictionary is quite similar to the non-generic hashtable. The advantage of Dictionary is, it is generic type. Dictionary is defined under System.Collections.Generic namespace. It is dynamic in nature means the size of the dictionary is growing
5 min read
Difference between Ref and Out keywords in C#
The out is a keyword in C# which is used for the passing the arguments to methods as a reference type. It is generally used when a method returns multiple values. The out parameter does not pass the property. Example : // C# program to illustrate the // concept of out parameter using System; class GFG { // Main method static public void Main() { //
3 min read
Difference between Abstract Class and Interface in C#
An abstract class is a way to achieve abstraction in C#. To declare an abstract class, we use the abstract keyword. An Abstract class is never intended to be instantiated directly. This class must contain at least one abstract method, which is marked by the keyword or modifier abstract in the class definition. The Abstract classes are typically use
4 min read
Collections in C#
.math-table { border-collapse: collapse; width: 100%; } .math-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .math-table th { border: 1px solid #5fb962; padding: 8px; } .math-table tr&gt;th{ background-color: #c6ebd9; vertical-align: middle; } .math-table tr:nth-child(odd) { background-color: #ffffff; } Collectio
5 min read
Introduction to .NET Framework
The .NET Framework is a software development framework developed by Microsoft that provides a runtime environment and a set of libraries and tools for building and running applications on Windows operating systems. The framework includes a variety of programming languages, such as C#, F#, and Visual Basic, and supports a range of application types,
7 min read
Common Language Runtime (CLR) in C#
The Common Language Runtime (CLR) is a component of the Microsoft .NET Framework that manages the execution of .NET applications. It is responsible for loading and executing the code written in various .NET programming languages, including C#, VB.NET, F#, and others. When a C# program is compiled, the resulting executable code is in an intermediate
6 min read
Introduction to C# Windows Forms Applications
Windows Forms is a Graphical User Interface(GUI) class library which is bundled in .Net Framework. Its main purpose is to provide an easier interface to develop the applications for desktop, tablet, PCs. It is also termed as the WinForms. The applications which are developed by using Windows Forms or WinForms are known as the Windows Forms Applicat
4 min read
C# | List Class
List&lt;T&gt; class represents the list of objects which can be accessed by index. It comes under the System.Collections.Generic namespace. List class can be used to create a collection of different types like integers, strings etc. List&lt;T&gt; class also provides the methods to search, sort, and manipulate lists. Characteristics: It is different
6 min read
C# | Encapsulation
Encapsulation is defined as the wrapping up of data and information under a single unit. It is the mechanism that binds together the data and the functions that manipulate them. In a different way, encapsulation is a protective shield that prevents the data from being accessed by the code outside this shield. Technically in encapsulation, the varia
5 min read
C# | Method Overriding
Method Overriding in C# is similar to the virtual function in C++. Method Overriding is a technique that allows the invoking of functions from another class (base class) in the derived class. Creating a method in the derived class with the same signature as a method in the base class is called as method overriding. In simple words, Overriding is a
8 min read
Hello World in C#
The Hello World! program is the most basic and first program when you dive into a new programming language. This simply prints the Hello World! on the output screen. In C#, a basic program consists of the following: A Namespace DeclarationClass Declaration &amp; DefinitionClass Members(like variables, methods etc.)Main MethodStatements or Expressio
3 min read
C# | Indexers
Prerequisite: Properties in C#An indexer allows an instance of a class or struct to be indexed as an array. If the user will define an indexer for a class, then the class will behave like a virtual array. Array access operator i.e ([ ]) is used to access the instance of the class which uses an indexer. A user can retrieve or set the indexed value w
5 min read
C# | Delegates
A delegate is an object which refers to a method or you can say it is a reference type variable that can hold a reference to the methods. Delegates in C# are similar to the function pointer in C/C++. It provides a way which tells which method is to be called when an event is triggered. For example, if you click on a Button on a form (Windows Form a
6 min read
C# | Inheritance
Introduction: Inheritance is a fundamental concept in object-oriented programming that allows us to define a new class based on an existing class. The new class inherits the properties and methods of the existing class and can also add new properties and methods of its own. Inheritance promotes code reuse, simplifies code maintenance, and improves
7 min read
C# | Generics - Introduction
Generic is a class which allows the user to define classes and methods with the placeholder. Generics were added to version 2.0 of the C# language. The basic idea behind using Generic is to allow type (Integer, String, … etc and user-defined types) to be a parameter to methods, classes, and interfaces. A primary limitation of collections is the abs
6 min read
C# | Class and Object
Class and Object are the basic concepts of Object-Oriented Programming which revolve around the real-life entities. A class is a user-defined blueprint or prototype from which objects are created. Basically, a class combines the fields and methods(member function which defines actions) into a single unit. In C#, classes support polymorphism, inheri
5 min read
C# | Arrays
An array is a group of like-typed variables that are referred to by a common name. And each data item is called an element of the array. The data types of the elements may be any valid data type like char, int, float, etc. and the elements are stored in a contiguous location. Length of the array specifies the number of elements present in the array
13 min read
C# | Constructors
A constructor is a special method of the class which gets automatically invoked whenever an instance of the class is created. Like methods, a constructor also contains the collection of instructions that are executed at the time of Object creation. It is used to assign initial values to the data members of the same class. Example : class Geek { ...
6 min read
C# | Operators
Operators are the foundation of any programming language. Thus the functionality of C# language is incomplete without the use of operators. Operators allow us to perform different kinds of operations on operands. In C#, operators Can be categorized based upon their different functionality : Arithmetic OperatorsRelational OperatorsLogical OperatorsB
15 min read
C# | Data Types
Data types specify the type of data that a valid C# variable can hold. C# is a strongly typed programming language because in C#, each type of data (such as integer, character, float, and so forth) is predefined as part of the programming language and all constants or variables defined for a given program must be described with one of the data type
7 min read
Article Tags :