Select Page

Thread priorities in the .NET framework are more complex than many developers think. Setting Thread priority is more than just adjusting the ThreadPriority of a Thread. You also have to take into account the priority of the process to which the threads belong.

The ProcessPriorityClass

Setting ThreadPriority to one of the values possible with C# will only shift the priority of the thread up and down within a class of priorities shared by the whole process. This means that even setting ThreadPriority to ThreadPriority.Highest will not actually give the thread a high priority, compared to the system processes. It will only give the thread a high priority compared to other threads belonging to comparable processes.
I”l try to make it a bit clearer with this little css/ascii illustration 🙂

Full system priority range: 1-31

In C# processes start with normal priority, so setting ThreadPriority.Highest under normal conditions wont make the thread higher priority than ThreadPriority.Lowest in a process running with a high priority class.

Letting Windows know that you are really important.

Take a look at this code:

class Program
  static void Main(string[] args)
    Thread t = new Thread(threadFunc);
    Process.GetCurrentProcess().PriorityClass = ProcessPriorityClass.RealTime;
    t.Priority = ThreadPriority.Highest;

  static void threadFunc()
    while (true) {}

This code will make a thread/process that has the highest possible priority you can set with C#. Luckily i have a dual-core processor – otherwise that code would have frozen my computer. Now it only uses up one of my cores frantically checking if true is still true…
The magic here lies in assigning ProcessPriorityClass.RealTime to the current process. Note that this is done in a process-wide scope, and all the threads in the process will have their priorities adjusted to fit in the new priority range. You can not have threads with extremely high and extremely low priorities within the same process.

It is really cool – but don’t abuse it.

Do not run off and adjust the priorities of all your programs, to get the processing time they rightly deserve. Fixing problems by raising priorities are very often a symptom of some greater underlying problem in your code, and the correct way of fixing things are most often to remove the bottlenecks in your program, and leave the priorities alone. This holds especially true for ProcessPriorityClass.RealTime, since this will potentially block execution of critical system stuff like garbage collection or keyboard and mouse input.
I would recommend against using anything higher than ProcessPriorityClass.High