【发布时间】:2016-10-12 06:33:40
【问题描述】:
我想通过我的 WinForm 应用程序实时获取控制台应用程序的输出(与通过 cmd.exe 运行相同)。我在非 UI 线程中执行的所有操作(使用 BackgroundWorker 的方法 bwRezerve_DoWork)。 AddTextToTextbox 使用 Invoke 更新 UI。
但现在我只在应用程序退出时才收到输出。 我在这里和其他网站上阅读了很多问题,阅读了类似的问题Capture output of process synchronously (i.e. "when it happens"),但仍然找不到解决方案。 这里代码sn-p:
private void bwRezerve_DoWork(object sender, DoWorkEventArgs e)
{
proc = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = Application.StartupPath + Path.DirectorySeparatorChar + "7z.exe",
Arguments = e.Argument,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true,
}
};
proc.EnableRaisingEvents = true;
proc.OutputDataReceived += (who, what) => AddTextToTextbox(what.Data);
proc.ErrorDataReceived += (who, what) => AddTextToTextbox(what.Data);
proc.Start();
proc.BeginOutputReadLine();
proc.BeginErrorReadLine();
//same result with next line commented
proc.WaitForExit(5 * 60 * 1000);
}
我也试过这个而不是OutputDataReceived,但结果是一样的
while (!proc.StandardOutput.EndOfStream)
{
string line = proc.StandardOutput.ReadLine();
AddTextToTextbox(line);
}
【问题讨论】:
标签: c# winforms process real-time stdout