Sponsored Ad

Thursday, June 3, 2010

How to set Priority of a Thread in C# | Example

How to set Priority of a Thread in C# | Example

While running the application in multithreaded application, a priority task need to finish first. C# allowes to set the priority of a thread by assigning the thread priority.

These are different types of thread priorities available in C#:

Zero

BelowNormal

Normal

AboveNormal

Highest

you can check the output of this program. the thread2 is started first but thread1 executed first and thread2 executed second. this is because thread1 have hieghest priority and thread2 have lowest priority.

sometimes the output of given program can differ from current one, because thread based program dipends on system configuration and running programs also.

 

How to set Priority of a Thread in C# | Example

using System;
using System.Text;
using System.Threading;

namespace Console_App
{

    public class Class1
    {
        public void fun1()
        {
            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine(" Thread-1 #" + i  );            
            }
        }

        public void fun2()
        {
            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine(" Thread-2 #" + i);
            }
        }
    }
    public class Class2
    {
        public static void Main()
        {
            Class1 a = new Class1();
            Thread thread1 = new Thread(new ThreadStart(a.fun1));
            Thread thread2 = new Thread(new ThreadStart(a.fun2));
            thread1.Priority = ThreadPriority.Highest;
            thread2.Priority = ThreadPriority.Lowest;
            thread2.Start();
            thread1.Start();
            Console.ReadLine();
        }
    }
}

No comments:

Post a Comment

Sponsored Ad

Development Updates