【发布时间】:2016-01-17 13:20:25
【问题描述】:
我有两个控制台应用程序,第一个是“Process1”,它编译为exe,无法更改其中的代码。 第二个是一个“仪表”控制台应用程序,用于计算 Process1 的启动时间。我想要现在的时刻 在控制台窗口中打印 HelloWorld 时。
// {我的流程1}: //我把它编译成一个名为process1.exe的程序集。
Class Process1{
static void Main(String[] args]){
Console.Write("Hello word");
}
}
我的第二个应用程序是一个控制台应用程序,它调用 process1.exe 作为进程,我想知道什么时候 process1 已“准备好”,假设它是打印“Hello Word”的时间。我读到了 Process.OutputDataReceived 事件, 但是调试时从不触发事件,里面的代码从不打印。
// {计量应用}
public Class Student{
String ID;
String Name;
}
public Class Program{
public static void Main(String[] args){
p.StartInfo = new ProcessStartInfo("process1.exe")
{
UseShellExecute = false,
//Add this line
RedirectStandardOutput = true,
};
Student st = new Student();
p.OutputDataReceived += P_OutputDataReceived;
p.Start();
//Add this line
p.BeginOutputReadLine();
p.WaitForExit();
}
private static void P_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
string output = e.Data;
Console.WriteLine("Process1 ready at: "+DateTime.Now);
Console.WriteLine("Data is: " + output);
}
}
【问题讨论】:
-
也许在
p.Start()之后添加p.WaitForExit();?您也可以直接在处理程序中Console.WriteLine(e.Data)进行调试。您还需要在ProcessStartInfo对象的属性中添加RedirectStandardOutput = true,否则将永远不会调用处理程序。 -
嗨@MaximilianGerhardt,我添加了WaitForExit() - 已更新。该事件仍未被触发。我尝试将句柄函数更改为始终 print e.Data private static void P_OutputDataReceived(object sender, DataReceivedEventArgs e) { string output = e.Data; Console.WriteLine("数据为:" + output); } 但没有打印出来。
-
放置断点并收集
-
操作,是的,因为它在
p.Start()之后缺少p.BeginOutputReadLine();,请参阅stackoverflow.com/a/285841/5296568 -
@MaximilianGerhardt,谢谢,成功了,我会更新代码
标签: c# console event-handling stdout