检查进程是否返回错误 C#

R.C*_*R.C 7 .net c# asp.net

声明并启动以下流程后:

System.Diagnostics.Process _p = new System.Diagnostics.Process();
.....
.....
....
_p.Start();
Run Code Online (Sandbox Code Playgroud)

现在有两种可能性:输出或错误.

如果发生错误,是否有Process类的属性可以通过它来确定是否发生错误?

我正在重定向标准输出,我不想在MSDN中警告重定向标准错误.我也不想使用:BeginOutputReadLine();

还有其他选择吗?

谢谢.

SWe*_*eko 12

我有一个需要启动进程并等待它们退出的服务,我使用类似的东西:

process.Start();
int timeout = ... // some normal value in milliseconds

process.WaitForExit(timeout);

try
{
   //ExitCode throws if the process is hanging
   return (CommandErrorCode)process.ExitCode;
}
catch (InvalidOperationException ioex)
{
   return CommandErrorCode.InternalError;
}
Run Code Online (Sandbox Code Playgroud)

在哪里CommandErrorCode是这样的

public enum CommandErrorCode
{
    Success = 0,
    //some other values I know from the processes that are managed
    InternalError = 256 // the ExitCode is a byte, so this out of that range
}
Run Code Online (Sandbox Code Playgroud)

顺便说一句,我重定向标准输出和标准错误,并使用BeginXXXReadLine和XXXDataReceived处理程序,并没有任何问题,但我使用的过程是已知的,定义良好的,并且表现良好.

  • 如果进程在超时期限内正常退出,则`ExitCode`返回一个值.如果进程挂起,它将根本不会退出,并且在正在运行的进程上调用`ExitCode`将导致抛出`InvalidOperationException`.您还可以使用`Process.Exited`事件和`Process.Kill`​​方法来管理进程生命周期. (2认同)