C Sharp ThreadPriority

C# ThreadPriority

In C# we can change the priority of the thread. The thread with the highest priority is thus executed first. The thread is however highly system dependent, thus it is not guaranteed but the chance of the execution of the high priority thread before low priority thread is increased.

Example:

using System;  
using System.Threading;  
 
public class Example  
{  
    public void thrd1()  
    {  
        Thread x = Thread.CurrentThread;  
        Console.WriteLine("The running thread is: " + x.Name);  
    }  
}  
public class thrd2  
{  
    public static void Main()  
    {  
        Example thrd = new Example();  
        Thread x = new Thread(new ThreadStart(thrd.thrd1));  
        Thread y = new Thread(new ThreadStart(thrd.thrd1));  
        Thread z = new Thread(new ThreadStart(thrd.thrd1));  
        x.Name = "ONE";  
        y.Name = "TWO";  
        z.Name = "THREE";  
        z.Priority = ThreadPriority.Highest;  
        y.Priority = ThreadPriority.Normal;  
        x.Priority = ThreadPriority.Lowest;  
        x.Start();
        y.Start();  
        z.Start();  
    }  
}

Output:

Explanation:

In the above example, the priority of the thread is changed. Here, the threads are highly system dependent, thus it may follow any algorithm preemptive or non-preemptive causing the output to be unpredictable.

Please Share