C#处理标准输出延迟

在C#表单中,我运行的进程启动信息类似于Redirect控制台输出到单独程序中的文本框和运行时的C#get进程输出 ,该进程正确运行 ,但输出需要很长时间才能出现在DataReceived事件中 。

我想在进程生成后立即看到文本; 根据Process标准输出无法捕获? (第一条评论)我需要等到事件被触发之前填充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完全缓冲:

如果已知stdout不引用交互设备,则流被完全缓冲 。 否则,它是依赖于库的,无论流是行缓冲还是默认缓冲 (参见setvbuf )。 资源

因此,除非您可以更改控制台程序源以禁用缓冲,否则在GUI程序端无法执行任何操作。