在启动进程之前为进程分配优先级

时间:2013-01-13 19:20:48

标签: c#

我有一个特定数量的进程(C#.exe)应该启动。我如何根据他们的优先级启动它们。

我知道Process.PriorityClass的东西,但它并没有用,因为它只在启动进程后分配优先级。

我这里有这个代码(不比较优先级)但它不起作用,因为没有运行进程所以我不能为它们分配优先级:

Process process1 = new Process();    
Process process2 = new Process();
Process process3 = new Process();

process1.StartInfo.FileName = "proc1";

process2.StartInfo.FileName = "proc2"'

process3.StartInfo.FileName = "proc3";

process1.PriorityClass = ProcessPriorityClass.AboveNormal;

process2.PriorityClass = ProcessPriorityClass.BelowNormal;

process3.PriorityClass = ProcessPriorityClass.High;

process2.Start();

process2.WaitForExit();

process1.Start();

process1.WaitForExit();

process3.Start();

1 个答案:

答案 0 :(得分:1)

您可以使用进程文件名创建一个Dictionary,然后使用Linq查询通过ProcessPriorityClass和OrderBy对它们进行排序。然后你只需要执行它们迭代列表并使用值来分配正确的优先级。

public void StartProcessesByPriority(Dictionary<String, ProcessPriorityClass> values)
{
    List<KeyValuePair<String, ProcessPriorityClass>> valuesList = values.ToList();

    valuesList.Sort
    (
        delegate(KeyValuePair<String, ProcessPriorityClass> left, KeyValuePair<String, ProcessPriorityClass> right)
        {
            return left.Value.CompareTo(right.Value);
        }
    );

    foreach (KeyValuePair<String, ProcessPriorityClass> pair in valuesList)
    {
        Process process = new Process();
        process.StartInfo.FileName = pair.Key;
        process.Start();

        process.PriorityClass = pair.Value;

        process.WaitForExit();
    }
}