【发布时间】:2011-02-14 19:40:50
【问题描述】:
我正在调用一个不断向控制台窗口输出信息的外部命令行应用程序。我想阅读这些信息并将其传递到我的代码中以报告进度。
但是...我从来没有得到任何回报。如果我使用 sr.ReadToEnd(),它会一直卡住,直到应用程序关闭并且返回一个空字符串。我需要做什么才能正确读取外部应用程序命令行窗口中的文本?
这是我的测试代码,不需要线程化,无论我做什么,流都会返回空:
private void runApp(string args, string app)
{
ProcessStartInfo pInfo = new ProcessStartInfo(app, args);
pInfo.CreateNoWindow = true;
pInfo.RedirectStandardOutput = true;
pInfo.UseShellExecute = false;
Thread t = new Thread(getProgress);
t.Start();
p = Process.Start(pInfo);
p.WaitForExit();
p.Close();
}
private void getProgress()
{
StreamReader sr = p.StandardOutput;
//Get's stuck here until the app closes, nothing is ever outputted
string output = sr.ReadLine();
//Just for testing, debugging here
while (true)
{
Console.WriteLine(output);
System.Threading.Thread.Sleep(1000);
}
sr.Close();
}
【问题讨论】: