Thread Priority

A thread’s Priority property determines how much execution time it gets relative to other active threads in the operating system, on the following scale:

enum ThreadPriority { Lowest, BelowNormal, Normal, AboveNormal, Highest }

The following code example shows the result of changing the priority of a thread. Two threads are created and the priority of one thread is set to BelowNormal. Both threads increment a variable in a while loop and run for a set time.

Example

using System;
using System.Threading;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main()
        {
            PriorityTest priorityTest = new PriorityTest();
            ThreadStart startDelegate =
                new ThreadStart(priorityTest.ThreadMethod);

            Thread threadOne = new Thread(startDelegate);
            threadOne.Name = "ThreadOne";
            Thread threadTwo = new Thread(startDelegate);
            threadTwo.Name = "ThreadTwo";

            threadTwo.Priority = ThreadPriority.BelowNormal;
            threadOne.Start();
            threadTwo.Start();

            // Allow counting for 10 seconds.
            Thread.Sleep(10000);
            priorityTest.LoopSwitch = false;
        }
    }

    class PriorityTest
    {
        bool loopSwitch;

        public PriorityTest()
        {
            loopSwitch = true;
        }

        public bool LoopSwitch
        {
            set { loopSwitch = value; }
        }

        public void ThreadMethod()
        {
            long threadCount = 0;

            while (loopSwitch)
            {
                threadCount++;
            }
            Console.WriteLine("{0} with {1,11} priority " +
                "has a count = {2,13}", Thread.CurrentThread.Name,
                Thread.CurrentThread.Priority.ToString(),
                threadCount.ToString("N0"));
        }
    }
}