我如何才能监听控制台命令的输出,并在侦听器之外对其做出反应
本文关键字:侦听器 监听 控制台 输出 命令 | 更新日期: 2023-09-27 18:27:38
我正在听我正在执行的控制台命令的输出:
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块中捕获该异常,但该异常没有被捕获。
如果您试图等待然后返回值,则不希望立即对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.