Recipe8.17.Boosting the Priority of a Process Programmatically


Recipe 8.17. Boosting the Priority of a Process Programmatically

Problem

You want a specific program to run at a higher priority than most of the other processes on the machine to help it complete a time-critical task.

Solution

Use the ProcessStartInfo and Process classes to launch the program and then adjust it to a higher priority like this:

 // Run recursive dir operation on the c:\ drive ProcessStartInfo psi = new ProcessStartInfo("cmd.exe","/C\"dir c:\\ /S\""); // Don't show the window. psi.CreateNoWindow = true; // Start the process. Process p = Process.Start(psi); // Raise the process priority to AboveNormal. p.PriorityClass = ProcessPriorityClass.AboveNormal; 

Discussion

The Process.PriorityClass property takes one of the ProcessPriorityClass enumeration values to indicate what priority the process should have. The enumeration values and descriptions are listed in Table 8-5.

Table 8-5. ProcessPriorityClass enumeration values

Name

Description

Idle

Run only when the system is idle. Preempted by any action.

BelowNormal

Will run with a light load on the CPU but will be preempted by any normal or higher process.

Normal

This is the default priority processes run at.

AboveNormal

A boost in scheduling priority from a normal process.

High

Used for time-critical tasks. Use carefully as it can eat most of the processor time and starve other applications.

RealTime

The highest possible priority. This should be used only when the process being altered is the only task that needs to occur on the machine.


Setting the priority above AboveNormal should be done in only very specialized situations for short durations of time, as it can starve other processes on the machine. The operating system uses the priority level to determine scheduling for the processors, and if one process is set to a higher priority for a long time, the processes with lesser priority may never finish.

See Also

See the "Process Class," "ProcessStartInfo Class," and "ProcessPriorityClass Enumeration" topics in the MSDN documentation.



C# Cookbook
Secure Programming Cookbook for C and C++: Recipes for Cryptography, Authentication, Input Validation & More
ISBN: 0596003943
EAN: 2147483647
Year: 2004
Pages: 424

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