C# 如何侦听控制台命令的输出并在侦听器之外对其作出反应?
我正在侦听我正在执行的控制台命令的输出:C# 如何侦听控制台命令的输出并在侦听器之外对其作出反应?,c#,C#,我正在侦听我正在执行的控制台命令的输出: Process p = new System.Diagnostics.Process(); ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo(); info.FileName = "cmd.exe"; info.RedirectStandardInput = true; info.RedirectStandardOutput = true; info.RedirectStan
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();
Process p=new System.Diagnostics.Process();
ProcessStartInfo=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+=新的DataReceivedEventHandler(
委托(对象发送方、DataReceivedEventArgs e)
{
Console.WriteLine(“接收数据:+e.data”);
如果(如数据=“失败”)
{
//我需要在代表之外对此做出反应,
//例如,停止流程并返回。
}
}
);
p、 StartInfo=info;
p、 Start();
使用(StreamWriter sw=p.StandardInput)
{
if(sw.BaseStream.CanWrite)
{
sw.WriteLine(“echo Hello World 1”);
软件写入线(“回波失败”);
sw.WriteLine(“回声你好世界2”);
sw.WriteLine(“echo Hello World 3”);
西南写入线(“退出”);
}
}
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.
@Frunk这不是Java,所以
==
也可以。这两个进程正在异步通信,因此对带外失败
消息做出反应可能太晚。下面是一个与您修改过的程序相关的示例,它使用了一个小小的hack-rough,使用AutoResetEvent
将信号从读卡器发送到写卡器,但是它有一些严重的竞争条件,因此您不应该在生产中使用它。