重定向标准输出在进程执行期间不会刷新
本文关键字:刷新 执行期 标准输出 进程 重定向 | 更新日期: 2023-09-27 18:35:22
我有一个控制台应用程序,我想在 c# 应用程序中处理 std。
基本上我已经设法用这段代码做到这一点:
Process ProcessObj = new Process();
ProcessObj.StartInfo.WorkingDirectory = WorkingPath;
ProcessObj.StartInfo.FileName = ApplicationPath;
ProcessObj.StartInfo.Arguments = ApplicationArguments;
ProcessObj.StartInfo.UseShellExecute = false;
ProcessObj.StartInfo.CreateNoWindow = true;
ProcessObj.StartInfo.RedirectStandardOutput = true;
// Start the process
ProcessObj.Start();
// loop through until the job is done
bool stopper = false;
while (!stopper)
{
stopper = ProcessObj.WaitForExit(100);
string line = null;
// handle normal outputs (loop through the lines)
while (true)
{
line = ProcessObj.StandardOutput.ReadLine();
if (line == null)
break;
Logger.Trace("Out: '"" + line + "'"");
}
}
当进程仅运行几秒钟时,看起来整个事情都在工作,没有任何问题。当我更改控制台应用程序的配置以计算更多内容时,该进程正在运行数小时。此时,我的 C# 应用程序没有收到来自控制台应用的响应。由于控制台应用程序是隐藏的,因此看起来应用程序卡住了,但事实并非如此。它已经在后台运行,似乎所有 std 输出仅在控制台应用完成执行时才通过管道传输到我的 c# 应用。所以问题是,我在我的 c# 应用程序中看不到 std 输出行。控制台应用完成后,它将在数小时后刷新。
有没有办法清除此标准重定向?有人知道为什么这不像我想要的那样工作吗?
PS:当我在普通cmd窗口中独立执行控制台应用程序时,输出会实时显示,没有任何问题。
请帮忙。
尝试在应用程序运行时读取输出?并将其保存到缓冲区?然后在应用程序退出时处理输出。
伪东西
string buffer = string.Empty;
while(!process.HasExited)
{
string line = process.Stream.ReadLine();
if (line != null)
buffer += Enviorment.Newline + line
}
// Do stuff without put here
Console.Write(buffer);