C# ThreadPriority
In C#, threads are used to execute multiple instructions concurrently. Thread priority is used to determine the importance of a thread relative to other threads in the same process. In this tutorial, we'll discuss how to set and retrieve thread priority in C#.
Syntax
The syntax for setting and retrieving thread priority in C# is as follows:
// Set thread priority
myThread.Priority = ThreadPriority.High;
// Get thread priority
ThreadPriority priority = myThread.Priority;
The ThreadPriority enumeration provides four priority levels: Highest, AboveNormal, Normal, and BelowNormal.
Example
Let's say we want to create a thread that performs a long-running operation and set its priority to "AboveNormal". Here's how we can implement it:
using System;
using System.Threading;
public class Worker {
public void LongRunningOperation() {
Console.WriteLine("Long running operation started.");
Thread.Sleep(5000);
Console.WriteLine("Long running operation completed.");
}
}
public class Program {
static void Main(string[] args) {
Worker workerObject = new Worker();
Thread workerThread = new Thread(workerObject.LongRunningOperation);
workerThread.Priority = ThreadPriority.AboveNormal;
workerThread.Start();
Console.WriteLine("Main thread completed.");
}
}
Output
When we run the example code above, the output will be similar to:
Long running operation started.
Main thread completed.
Long running operation completed.
This is because the main thread completed before the long-running operation completed.
Explanation
In the example above, we created a worker object that performs a long-running operation in its LongRunningOperation
method. We then created a thread object and passed the LongRunningOperation
method to its constructor. We set the thread priority to "AboveNormal" and started the thread.
When we ran the program, the "Main thread completed" message was printed to the console before the long-running operation completed, because it had a lower priority than the worker thread.
Use
Thread priority is used to indicate the relative importance of one thread compared to other threads. Thread priority can be used to ensure that high-priority threads receive more CPU time than low-priority threads.
Important Points
- A higher thread priority value indicates a higher priority.
- It is not recommended to set thread priority to Highest or Lowest, as it can lead to poor performance or system instability.
- Low-priority threads are not always executed immediately, and high-priority threads can be starved if too many low-priority threads are running.
Summary
In this tutorial, we discussed how to set and retrieve thread priority in C#. We covered the syntax, example, output, explanation, use, and important points of setting thread priority in C#. With this knowledge, you can now use thread priority in your C# code to indicate the relative importance of one thread compared to other threads.