Tuesday, 21 August 2018

C#: Prioritizing threads

By giving priorities to threads, we can inform the operating system, that give more importance to highest priority threads, and low importance to low priority threads. Higher priority threads get more CPU time than low priority threads.

How to set priority to a thread?
C# Provides enum constants to set the priorities to a thread.

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

By setting the 'Priority' property of a thread, you can change the priority of thread.

Thread t = new Thread(Print);
t.Priority = ThreadPriority.Highest;

Program.cs
using System.Threading;
using System;

namespace ThreadingTutorial
{
    class HelloWorld
    {
        static void Main()
        {
            Thread highPriority = new Thread(processData);
            highPriority.Priority = ThreadPriority.Highest;
            highPriority.Name = "Higher Priority Thread";

            Thread lowerPriority = new Thread(processData);
            lowerPriority.Priority = ThreadPriority.Lowest;
            lowerPriority.Name = "Lower Priority Thread";

            lowerPriority.Start();
            highPriority.Start();
        }

        static void processData()
        {
            int k = 987654321;

           for(int i=1; i < 1000000000; i++)
            {
                k = k * i;
            }

            Console.WriteLine("{0} Finished Execution", Thread.CurrentThread.Name);
        }
    }
}

Output
Higher Priority Thread Finished Execution

Lower Priority Thread Finished Execution




Previous                                                 Next                                                 Home

No comments:

Post a Comment