我从 C# 表单运行 process开始信息类似于 Redirect console output to textbox in separate program和 C# get process output while running , 该过程运行正确,但输出需要很长时间才能出现在 DataReceived event 中.
我想在进程生成文本后立即看到它;根据 Process standard output cannot be captured? (第一条评论)我需要等到 2 到 4 kb 的缓冲区填充后才能触发事件。
根据要求,这是代码:
void pcs_OutputDataReceived(object sender, System.Diagnostics.DataReceivedEventArgs e)
{
if (!string.IsNullOrEmpty(e.Data))
textBox1.BeginInvoke((Action)delegate { textBox1.AppendText(text + "\n"); });
}
private void LER_Go_Click(object sender, EventArgs e)
{
// variables LiDARExtRep contains the full path to an executable file
// that runs in DOS and produces verbose output.
// LER_Path.Text is the parameter passed to LiDARExtRep (only one arg for this example)
ProcessStartInfo pStartInfo = new ProcessStartInfo(LiDARExtRep, LER_Path.Text);
pStartInfo.UseShellExecute = false;
pStartInfo.ErrorDialog = false;
pStartInfo.RedirectStandardError = true;
pStartInfo.RedirectStandardInput = true;
pStartInfo.RedirectStandardOutput = true;
pStartInfo.CreateNoWindow = true;
System.Diagnostics.Process pcs = new System.Diagnostics.Process();
pcs.StartInfo = pStartInfo;
bool pStarted = pcs.Start();
pcs.OutputDataReceived += new DataReceivedEventHandler(pcs_OutputDataReceived);
pcs.BeginOutputReadLine();
pcs.WaitForExit();
}
我没有看到它有什么特别之处,它与我引用的示例完全相同......构造函数中的一个简单的 "Dir","/b/s" 应该产生相同的结果。
有没有办法将缓冲区减少到几个字节,或者有更好的方法来执行命令行工具并“实时”接收输出?
背景:我用 C++ 写了很多命令行程序,很棒,但年轻一代似乎害怕 DOS,所以我正在创建一个表单 (GUI) 来收集参数这些工具似乎比尝试在 C++ 中的每个程序上放置一个 GUI 工作要少很多。如果我无法获得实时响应,我将不得不 UseShellExecute = true; 并显示命令窗口。
请您参考如下方法:
缓冲发生在控制台程序结束时。默认情况下,如果已知要重定向,stdout 将被完全缓冲:
If
stdoutis known to not refer to an interactive device, the stream is fully buffered. Otherwise, it is library-dependent whether the stream is line buffered or not buffered by default (see setvbuf). Source
因此,除非您可以更改控制台程序源以禁用缓冲,否则在 GUI 程序端什么也做不了。
