简体   繁体   English

如何从C#中的进程中捕获异常

[英]How to catch exceptions from processes in C#

I have an acceptance runner program here that looks something like this: 我在这里有一个接受跑步者计划,看起来像这样:

public Result Run(CommandParser parser)
{
    var result = new Result();
    var watch = new Stopwatch();

    watch.Start();

    try
    {
        _testConsole.Start();

        parser.ForEachInput(input =>
        {
            _testConsole.StandardInput.WriteLine(input);
            return _testConsole.TotalProcessorTime.TotalSeconds < parser.TimeLimit;
        });

        if (TimeLimitExceeded(parser.TimeLimit))
        {
            watch.Stop();
            _testConsole.Kill();
            ReportThatTestTimedOut(result);
        }
        else
        {
            result.Status = GetProgramOutput() == parser.Expected ? ResultStatus.Passed : ResultStatus.Failed;
            watch.Stop();
        }
    }
    catch (Exception)
    {
        result.Status = ResultStatus.Exception;
    }

    result.Elapsed = watch.Elapsed;
    return result;
}

the _testConsole is an Process adapter that wraps a regular .net process into something more workable. _testConsole是一个Process适配器,它将常规的.net进程包装成更可行的东西。 I do however have a hard time to catch any exceptions from the started process (ie the catch statement is pointless here) I'm using something like: 但是我很难从启动过程中捕获任何异常(即catch语句在这里毫无意义)我正在使用类似的东西:

_process = new Process
                           {
                               StartInfo =
                                   {
                                       FileName = pathToProcess,
                                       UseShellExecute = false,
                                       CreateNoWindow = true,
                                       RedirectStandardInput = true,
                                       RedirectStandardOutput = true,
                                       RedirectStandardError = true,
                                       Arguments = arguments
                                   }
                           };

to set up the process. 建立过程。 Any ideas? 有任何想法吗?

Exceptions don't flow from one process to another. 异常不会从一个进程流向另一个进程。 The best you could do would be to monitor the exit code of the process - conventionally, an exit code of 0 represents success, and any other exit code represents an error. 您可以做的最好的事情是监视进程的退出代码 - 通常,退出代码0表示成功,任何其他退出代码表示错误。

Whether that's the case for the processes you're launching is a different matter, of course. 当然,对于你正在推出的流程来说,情况是否是另一回事。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM