C#线程优先级的必要性:如果在应用程序中有多个线程在运行,但一些线程比另一些线程重要,该怎么办在这种情况下,可以在一个进程中为不同的线程指定不同的优先级。一般情况下,如果有优先级较高的线程在工作,就不会给优先级较低的线程分配任何时间片,其优点是可以保证给接收用户输入的线程指定较高的优先级。在大多数的时间内,这个线程什么也不做,而其他线程则执行它们的任务。但是,如果用户输入了信息,这个线程就立即获得比应用程序中其他线程更高的优先级,在短时间内处理用户输入事件。
C#线程优先级的规律:高优先级的线程可以完全阻止低优先级的线程执行,因此在改变线程的优先级时要特别小心。线程的优先级可以定义为ThreadPriority枚举的值,即Highest、AboveNormal、Normal、BelowNormal和 Lowest。
注意,每个进程都有一个基本优先级,这些值与进程的优先级是有关系的。给线程指定较高的优先级,可以确保它在该进程中比其他线程优先执行,但系统上可能还运行着其他进程,它们的线程有更高的优先级。因此Windows给自己的操作系统线程指定高优先级。
在ThreadPlayaround示例中,对Main()方法做如下修改,就可以看出修改线程的优先级的效果:
- ThreadStart workerStart = new ThreadStart(StartMethod);
- Thread workerThread = new Thread(workerStart);
- workerThread.Name = "Worker";
- workerThread.Priority = ThreadPriority.AboveNormal;
- workerThread.Start();
其中,工作线程的优先级比主线程高,运行结果如下所示:
- ThreadPlayaroundWithPriorities
- Interval to display results at> 1000000
- Starting thread: Main Thread
- Main Thread: Current Culture = en-US
- Starting thread: Worker
- Worker: Current Culture = en-US
- Main Thread: count has reached 1000000
- Worker: count has reached 1000000
- Worker: count has reached 2000000
- Worker: count has reached 3000000
- Worker: count has reached 4000000
- Worker: count has reached 5000000
- Worker: count has reached 6000000
- Worker: count has reached 7000000
- Worker: count has reached 8000000
- Worker Thread Finished
- Main Thread: count has reached 2000000
- Main Thread: count has reached 3000000
- Main Thread: count has reached 4000000
- Main Thread: count has reached 5000000
- Main Thread: count has reached 6000000
- Main Thread: count has reached 7000000
- Main Thread: count has reached 8000000
- Main Thread Finished
这说明,当工作线程的优先级为AboveNormal时,一旦工作线程被启动,主线程就不再运行。
C#线程优先级的相关内容就向你介绍到这里,希望对你了解和学习C#线程优先级有所帮助。
【编辑推荐】