Open In App

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:



How to set and get the priority of thread?

Thread.Priority Property is used to get or set a value indicating the scheduling priority of a thread.

Syntax:



public ThreadPriority Priority{ get; set; }

Here, the ThreadPriority enum under System.Threading namespace is responsible for specifying the scheduling priority of a Thread and the priorities are:

Property Value: One of the ThreadPriority values. The default value is Normal.

Exceptions:

Example 1:




// C# program to illustrate how to
// set and get the priority of threads
using System;
using System.Threading;
  
class GFG {
  
    // Main Method
    static public void Main()
    {
  
        // Creating and initializing threads
        Thread T1 = new Thread(work);
        Thread T2 = new Thread(work);
        Thread T3 = new Thread(work);
  
        // Set the priority of threads
        T2.Priority = ThreadPriority.Highest;
        T3.Priority = ThreadPriority.BelowNormal;
        T1.Start();
        T2.Start();
        T3.Start();
  
        // Display the priority of threads
        Console.WriteLine("The priority of T1 is: {0}",
                                          T1.Priority);
  
        Console.WriteLine("The priority of T2 is: {0}",
                                          T2.Priority);
  
        Console.WriteLine("The priority of T3 is: {0}",
                                          T3.Priority);
    }
  
    public static void work()
    {
  
        // Sleep for 1 second
        Thread.Sleep(1000);
    }
}

Output:

The priority of T1 is: Normal
The priority of T2 is: Highest
The priority of T3 is: BelowNormal

Example 2:




// C# program to illustrate the
// Priority property of Thread class
using System;
using System.Threading;
  
class GFG {
  
    // Main Method
    static public void Main()
    {
  
        // Creating and initializing threads
        Thread T1 = new Thread(work1);
        Thread T2 = new Thread(work2);
  
        // Set the priority of threads
        // Here T2 thread executes first 
        // because the Priority of T2 is
        // highest as compare to T1 thread
        T1.Priority = ThreadPriority.Lowest;
        T2.Priority = ThreadPriority.Highest;
        T1.Start();
        T2.Start();
    }
    public static void work1()
    {
  
        Console.WriteLine("T1 thread is working..");
    }
    public static void work2()
    {
  
        Console.WriteLine("T2 thread is working..");
    }
}

Output:

T2 thread is working..
T1 thread is working..

Reference:


Article Tags :
C#