Thread Priorities  



Threads can have priorities over other threads. We can get or set the priority of a thread using the Priority property of the Thread class. We can set it to one of the following values

  • AboveNormal

  • BelowNormal

  • Highest

  • Lowest

  • Normal

These are nothing but members of the ThreadPriority enumeration 

namespace thread
{

using System ;
using System.Threading ;

class counterthraed
{

public int clicks = 0 ;
public void startcount ( )
{

while ( true )
{

clicks++ ;

}

}

}

 

public class Class1
{

public static int Main ( string [ ] args )
{

counterthraed c1 = new counterthraed ( ) ;
Thread t1=new Thread(new ThreadStart ( c1.startcount ) ) ;
t1.Priority = ThreadPriority.Highest ;
t1.Start( ) ;

counterthraed c2 = new counterthraed ( ) ;
Thread t2=new Thread(new ThreadStart ( c2.startcount ) ) ;
t2.Priority = ThreadPriority.Normal ;
t2.Start ( ) ;

t1.Abort ( ) ;
t2.Abort ( ) ;

Console.WriteLine ( "High Priority Thread Clicks: {0} ", 
c1.clicks ) ; 
Console.WriteLine ( "Low Priority Thread Clicks: {0}", 
c2.clicks ) ; 
return 0;

}

}

}

The output is:
High Priority Thread Clicks: 359461997
Low Priority Thread Clicks: 7020118

 
The thread t1 is given a higher priority over the thread t2 and hence the click count of t1 is more than t2 always. Whenever a conflict between t1 and t2 arises, t1 is allowed to execute and is given priority.