线程优先级从高到低分为:Highest 、AboveNormal、Normal、BelowNormal、Lowest共5个等级。通过设置Thread类的ThreadPriority属性(可读写属性)来调整。
范例:
下面的代码示例说明了更改线程优先级的结果。创建两个线程,其中一个线程的优先级设置为 BelowNormal。两个线程在 while 循环中都增加一个变量,并运行一段设定的时间。
using System;
using System.Threading;
class Test
{
static void Main()
{
PriorityTest priorityTest = new PriorityTest();
ThreadStart startDelegate =
new ThreadStart(priorityTest.ThreadMethod);
Thread threadOne = new Thread(startDelegate);
threadOne.Name = "ThreadOne";//通过设置线程的name加以区分。
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;
Console.ReadLine();
}
}
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"));
}
}
运行结果:很明显,高优先级的线程拥有更多的运行机会。