C# 如何启动低优先级的进程?C#
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1010370/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I launch a process with low priority? C#
提问by
I want to execute a command line tool to process data. It does not need to be blocking. I want it to be low priority. So I wrote the below
我想执行一个命令行工具来处理数据。它不需要阻塞。我希望它是低优先级的。所以我写了下面
Process app = new Process();
app.StartInfo.FileName = @"bin\convert.exe";
app.StartInfo.Arguments = TheArgs;
app.PriorityClass = ProcessPriorityClass.BelowNormal;
app.Start();
However, I get a System.InvalidOperationException
with the message "No process is associated with this object." Why? How do I properly launch this app in low priority?
但是,我收到System.InvalidOperationException
消息“没有进程与此对象关联”。为什么?如何以低优先级正确启动此应用程序?
Without the line app.PriorityClass = ProcessPriorityClass.BelowNormal;
the app runs fine.
没有这条线app.PriorityClass = ProcessPriorityClass.BelowNormal;
,应用程序运行良好。
采纳答案by Robert Harvey
Try setting the PriorityClass AFTER you start the process. Task Manager works this way, allowing you to set priority on a process that is already running.
尝试在开始该过程后设置 PriorityClass。任务管理器以这种方式工作,允许您为已经运行的进程设置优先级。
回答by Roger Lipscombe
If you're prepared to P/Invoke to CreateProcess
, you can pass CREATE_SUSPENDED
in the flags. Then you can tweak the process priority before resuming the process.
如果您准备 P/Invoke to CreateProcess
,则可以传入CREATE_SUSPENDED
标志。然后您可以在恢复进程之前调整进程优先级。
回答by Pablo Montilla
You can create a process with lower priority by doing a little hack. You lower the parent process priority, create the new process and then revert back to the original process priority:
您可以通过一些小技巧创建一个优先级较低的进程。您降低父进程优先级,创建新进程,然后恢复到原始进程优先级:
var parent = Process.GetCurrentProcess();
var original = parent.PriorityClass;
parent.PriorityClass = ProcessPriorityClass.Idle;
var child = Process.Start("cmd.exe");
parent.PriorityClass = original;
child
will have the Idle
process priority right at the start.
child
将Idle
在开始时拥有进程优先权。