如何监听控制台命令的输出并在侦听器之外作出反应?

时间:2014-10-23 14:14:08

标签: c#

我正在监听我正在执行的控制台命令的输出:

Process p = new System.Diagnostics.Process();
ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo();

info.FileName = "cmd.exe";
info.RedirectStandardInput = true;
info.RedirectStandardOutput = true;
info.RedirectStandardError = true;
info.UseShellExecute = false;
info.CreateNoWindow = true;

p.OutputDataReceived += new DataReceivedEventHandler(
    delegate (object sender, DataReceivedEventArgs e)
    {
        Console.WriteLine("Received data: " + e.Data);
        if (e.Data == "FAIL")
        {
            // I need to react to this outside the delegate,
            // e.g. stop the process and return <false>.
        }
    }

);

p.StartInfo = info;
p.Start();

using (StreamWriter sw = p.StandardInput)
{
    if (sw.BaseStream.CanWrite)
    {
        sw.WriteLine("echo Hello World 1");
        sw.WriteLine("echo FAIL");
        sw.WriteLine("echo Hello World 2");
        sw.WriteLine("echo Hello World 3");
        sw.WriteLine("exit");
    }
}

p.BeginOutputReadLine();
p.WaitForExit();

这可以按预期工作,但这里是我不知道该怎么做:当进程在其输出中生成“FAIL”行时,我想对委托之外的这个做出反应,即在方法中催生了这个过程。我怎样才能做到这一点?在我看来,我在委托中唯一的上下文是发送者(这是过程)和产生的数据。

我试图让委托抛出异常并在p.Start()和所有其他代码周围的try-catch块中捕获它,但异常不会被捕获。

1 个答案:

答案 0 :(得分:1)

如果您尝试等待然后返回值,则不希望立即对FAIL行作出反应。你应该做的是让你的代表设置一个标志。然后,您可以在p.WaitForExit来电后检查该国旗,并返回相应的值:

var hasFailed = false;

// Set up process

p.OutputDataReceived += new DataReceivedEventHandler(
    delegate (object sender, DataReceivedEventArgs e)
    {
        if (e.Data == "FAIL") hasFailed = true;
    }
);

// Start Process

p.WaitForExit();

if(hasFailed)
{
    // Handle the fact that the process failed and return appropriately.
}

// Otherwise the process succeeded and we can return normally.