C#中如何从进程中捕获异常 [英] How to catch exceptions from processes in C#

查看:74
本文介绍了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;
}

_testConsole 是一个进程适配器,它将常规的 .net 进程包装成更可行的进程.然而,我确实很难从启动的进程中捕获任何异常(即 catch 语句在这里毫无意义)我正在使用类似的东西:

the _testConsole is an Process adapter that wraps a regular .net process into something more workable. I do however have a hard time to catch any exceptions from the started process (i.e. the catch statement is pointless here) I'm using something like:

_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?

推荐答案

异常不会从一个进程流到另一个进程.您能做的最好的事情是监控进程的退出代码 - 通常,退出代码为 0 表示成功,任何其他退出代码表示错误.

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.

当然,您启动的流程是否属于这种情况是另一回事.

Whether that's the case for the processes you're launching is a different matter, of course.

这篇关于C#中如何从进程中捕获异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆