22.4 Changing the Priority of a Running Thread

 <  Day Day Up  >  

You want a thread to run at a higher or lower priority, due to the relative urgency of the work it is doing.


Technique

Simply change the priority using the Thread.Priority property:

 
 Thread.CurrentThread.Priority = ThreadPriority.Highest; 

To change the priority of another thread ( workerThread as in the preceding examples), use the following:

 
 workerThread.Priority = ThreadPriority.Highest; 

The choice of priorities comes from the ThreadPriority enumeration: possible values are Highest , AboveNormal , Normal , BelowNormal , and Lowest . If you don't set the priority explicitly, it defaults to Normal .

Comments

Be careful of changing thread priorities: in general, it's the kind of thing you should only do if you have a very good reason because of the risk of disrupting other tasks that have a lower priority. For example, a high-priority background thread that is engaged in intensive computations could prevent a user -interface thread from gaining any computer time and so prevent the application from responding to user input.

Setting the priority of a thread essentially provides a hint to the Windows operating system about the relative urgency of the work that thread is performing. Microsoft reserves the right to change the details of precisely how the operating system responds to these hints. However, for current versions of Windows, it is true to say that any thread is only ever given processor time when there are no higher-priority threads demanding that time. If there are any higher-priority threads, then low-priority threads are only able to execute while higher-priority threads are suspended or sleeping (for example, while waiting on thread synchronization primitives).

You should also bear in mind that thread priorities are only set relative to the process that contains those threads. Windows maintains a separate overall process priority for each process ”and the process priority takes precedence over thread priorities. In other words, all threads in a high-priority process take precedence over all threads in a lower-priority process, no matter what the individual thread priorities. If you want to change the process priority, you should look up the PriorityClass property of the System.Diagnostics.ProcessClass class in the MSDN documentation. Bear in mind, however, that changing process priority is potentially even more dangerous than changing thread priority within a process because of the potential to prevent other processes from running. Don't do it unless you know what you're doing and you have an extremely good reason for changing priorities!

 <  Day Day Up  >  


Microsoft Visual C# .Net 2003
Microsoft Visual C *. NET 2003 development skills Daquan
ISBN: 7508427505
EAN: 2147483647
Year: 2003
Pages: 440

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net