I am here to continue the discussion around Threading. Today we will discuss Thread Priority and related concepts.

In case you haven't seen my previous posts, you can go through the following:

Let’s start by posing some basic questions to understand the concepts.

Why we need Thread Priority

Well, this is not required in common cases; however, there are a few cases when you may want to elevate priority of some threads. One such example could be when you want certain talk to be completed first over others.

There are basically five types of thread priority:

Let’s take a simple example to understand better.

  1. static void DoWork1()
  2. {
  3. for (int i = 0; i < 5; i++)
  4. {
  5. Console.WriteLine("DoWork1: " + i);
  6. }
  7. }
  8. static void DoWork2() {
  9. for (inti = 0; i < 5; i++)
  10. {
  11. Console.WriteLine("DoWork2: " + i);
  12. }
  13. }
  14. static void Main(string[] args)
  15. {
  16. Console.Title = "Threading Priority Demo";
  17. Thread thread1 = new Thread(new ThreadStart(DoWork1));
  18. Thread thread2 = new Thread(new ThreadStart(DoWork2));
  19. thread1.Priority = ThreadPriority.Highest;
  20. thread2.Priority = ThreadPriority.Lowest;
  21. thread2.Start();
  22. thread1.Start();
  23. }
Output:

Output

You can see in above output that DoWork1 is getting executed first despite that thread2 or DoWork2 is begun first.

Why So?

It is because in the code we have set the thread1 priority as highest and thread2 priority as lowest.
Points to remember: