Open In App

C# Multithreading

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
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.

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.


Last Updated : 22 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads