Recommendation 76: Beware of thread priorities
Threads have 5 priorities in C #: Highest, AboveNormal, Normal, BelowNormal, and lowest. When you talk about the priority of a thread, it involves scheduling the thread. Windows system is a priority-based preemptive scheduling system. In a system, if a thread has a higher priority, and it is just in the ready state, the system will always run the thread first. In other words, high-priority threads always get more CPU execution time in the system scheduling algorithm.
We can test the following code in a single CPU system:
Static voidMain (string[] args) { LongT1num =0; LongT2num =0; CancellationTokenSource CTS=NewCancellationTokenSource (); Thread T1=NewThread (() = { while(true&&!CTS. token.iscancellationrequested) {T1num++; } }); T1. IsBackground=true; T1. Priority=threadpriority.highest; T1. Start (); Thread T2=NewThread (() = { while(true&&!CTS. token.iscancellationrequested) {T2num++; } }); T2. IsBackground=true; T2. Start (); Console.ReadLine (); //stopping a threadCTS. Cancel (); Console.WriteLine ("T1num:"+t1num.tostring ()); Console.WriteLine ("T2num:"+t2num.tostring ()); }
As a result we will find that if this program runs on a single-core computer, the priority is highest thread T1, and its output value will almost always be greater than the priority normal (default) thread T2.
In C #, with thread and threadpool new threads, the default priority is normal. Although it is possible to modify the priority of a thread as in the example above, it is generally not recommended. Of course, if it is some very critical thread, we can still raise the priority of the thread. These key threads should have features such as short running times, instant access to wait states, and so on.
Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia
157 recommendations for writing high-quality code to improve C # programs--Recommendation 76: Beware of thread priorities