等待进程响应

Waiting for Process Response

所以在我的应用程序中,我正在启动一个新进程。我已将标准输入、标准输出和标准错误分别重定向到 StreamWriter 和 StreamReaders。

现在我想根据进程在其标准输出或标准错误中的响应方式采取相应的行动,我想知道是否有比像这样让我的项目进入休眠状态更好的方法:

p = Process.start(some.exe);
StreamWriter process_si = p.StandardInput;
StreamReader process_so = p.StandardOutput;
StreamReader process_se = p.StandardError;

System.Threading.Thread.Sleep(1000);
if(process.HasExited)
{
   Read standard Error...
}

else
{
   read the standard input...
}

我的想法是做这样的事情:

p = Process.start(some.exe);
StreamWriter process_si = p.StandardInput;
StreamReader process_so = p.StandardOutput;
StreamReader process_se = p.StandardError;

// Wait fro some type of response from the process
p.waitForStandardErrorOrStarndardOut();

if(process_se contains message)
{
   Read standard Error...
}

else if(process_so contains message)
{
   read the standard input...
}

有什么简单的等待响应的方法吗?我最好的猜测是创建我自己的等待响应函数,如下所示:

void waitForResponse(StreamReader errorOut, StreamReader standardOut)
{
   while(errorOut.isEmpty() && standardOut.isEmpty())
   {
      System.Threading.Thread.Sleep(10);
   }
}

如果您有任何问题,请告诉我。我发现了一些与我的相似的其他线程,但没有完全回答我的问题...

我将使用异步读取输出和错误流,如 documentation 中所述。 然后使用 WaitForExit() 方法让主线程休眠。

所以在代码中是:

void main()
{
    var psi = new ProcessStartInfo("fileName.exe", "<arguments>");
    psi.UseShellExecute = false;
    psi.RedirectStandardOutput = true;
    psi.RedirectStandardError = true;

    var p = Process.Start(psi);
    p.OutputDataReceived += p_OutputDataReceived;
    p.ErrorDataReceived += p_ErrorDataReceived;
    p.WaitForExit();
}
static void p_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
    //react on the received error data in e.Data.
}

static void p_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
    //react on the received output data in e.Data.
}