【问题标题】:Process.Start and allocated resourcesProcess.Start 和分配的资源
【发布时间】:2025-12-18 03:15:02
【问题描述】:

我有这段代码:

Process pLight = new Process();
pLight.StartInfo.UseShellExecute = false;
pLight.StartInfo.FileName = "MyCommand.exe";
//
pLight.StartInfo.Arguments = "-myparam 0";
pLight.Start();
//
pLight.StartInfo.Arguments = "-myparam 1";
pLight.Start();
//
pLight.StartInfo.Arguments = "-myparam 2";
pLight.Start();

问题是:每次调用Start() 时都会“创建”一个新进程?

来自Process.Start 文档:

如果进程资源已启动,则返回 true;如果没有启动新的进程资源(例如,如果重用现有进程),则为 false。

但每次我调用此方法时,我都会得到 true。那么我怎样才能重用相同的过程呢?有没有办法使用同一个进程运行多个命令?

【问题讨论】:

    标签: c# .net process resources


    【解决方案1】:

    如果我没看错,您需要做的就是创建一个 ProcessStartInfo 的新实例,然后如果有一个 Process 正在运行,它会重用它。

    通过指定 ProcessStartInfo 实例,使用此重载启动流程资源。重载将资源与新的 Process 组件相关联。如果进程已经在运行,则不会启动额外的进程资源。相反,现有的流程资源会被重用,并且不会创建新的流程组件。在这种情况下,Start 不会返回一个新的 Process 组件,而是将 null 返回给调用过程。

    http://msdn.microsoft.com/en-us/library/0w4h05yb.aspx(备注下第一行)

    【讨论】:

      【解决方案2】:
      pLightStartInfo = new ProcessStartInfo();
      pLightStartInfo.UseShellExecute = false;
      pLightStartInfo.FileName = "MyCommand.exe";
      pLightStartInfo.Arguments = "-myparam 0";
      pLightStart();
      pLightStartInfo.Arguments = "-myparam 1";
      pLightStart();
      pLightStartInfo.Arguments = "-myparam 2";
      
      Process pLight = new Process(pLightStartInfo); // first time so a new Process will be started
      
      Process myOtherProcess = Process.Start(pLightStartInfo); // second time so myOtherProcess would reuse pLight, given original hadn't closed so both would be "pointing" at one MyCommand.exe
      

      我自己从来没有做过,但这就是它的意思。

      【讨论】:

      • 不确定那个,(平等与等价)相同的进程ID/句柄是我想要的。
      • 这个答案只是推测,实际上不起作用(即使在必要的更正之后)。如果 pLight 以某种方式被“重用”,那么根据文档 myOtherProcess 将为空。不是。