C# thread priority – detail whatever you know

(Last Updated On: February 25, 2019)

Every C# thread has a priority. Thread priorities in C# are available in ThreadPriority class from namespace System.Threading; Below C# thread priority can be assigned to a thread.

  • Highest
  • AboveNormal
  • Normal
  • BelowNormal
  • Lowest

By default “Normal” thread priority is assigned to a thread in C#.

Thread scheduler of operating system schedules all threads according to their thread priority for execution, but with no guarantee. Operating system may or may not respect the priority of thread. Means, it is not necessary that highest priority thread will always execute first and lower priority thread will execute last. Lowest priority thread will run slower, but not completely stop.

Note that operating system do not ignore priority completely and always try to complete high priority task first.

If we execute the below software program – C# thread priority example, you should find completion of highest priority thread first most of the time.

Program for thread Priority in C#

To check the desired result i.e. high priority thread complete its task first and low priority threads complete at later on the basis of above concepts, we will consider three threads performing the same amount of task.

Also, to notice the desired result, we need to give long task to threads as for smaller task we will not be able to see execution of thread in priory order.

Here we have given highest priority to third thread and lowest priority to first one. In the result most of the time you would see the completion for the third thread first and first one to last.

 

Conclusion:

  • Thread scheduler of operating system schedule threads with no guarantee but tries to consider them.
  • For long running task threads get the benefit of priority setting.