等待过程响应

时间:2015-04-19 21:37:20

标签: c# process

所以在我的应用程序中,我正在启动一个新进程。我已将标准输入,标准输出和标准错误分别重定向到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);
   }
}

如果您有任何疑问,请与我们联系。我找到了一些类似于我的其他线程,但没有完全回答我的问题...

1 个答案:

答案 0 :(得分:2)

我会按照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.
}