C#进程标准输出延迟

本文关键字:延迟 标准输出 进程 | 更新日期: 2023-09-27 18:00:32

在C#窗体中,我正在运行一个进程,其启动信息类似于将控制台输出重定向到单独程序中的文本框,并且C#在运行时获得进程输出,进程运行正常,但输出需要很长时间才能出现在DataReceived事件中。

我希望在流程生成文本后尽快看到它;根据流程标准输出无法捕获?(第一条评论)我需要等到2到4kb的缓冲区填满后,事件才会被触发。

根据要求,这是代码:

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();
}

我看不出它有什么特别之处,它和我提到的例子完全一样。。。构造函数中的简单CCD_ 1应该产生相同的结果。

有没有办法将缓冲区减少到几个字节,或者有更好的方法来执行命令行工具并"实时"接收输出?

背景:我用C++编写了许多命令行程序,这些程序运行得很好,但年轻一代似乎害怕DOS,所以我正在创建一个表单(GUI)来收集这些工具的参数,因为这似乎比在C++中的每个程序上都放一个GUI少了很多工作。如果我无法获得实时响应,我将不得不使用UseShellExecute = true;并显示命令窗口。

C#进程标准输出延迟

缓冲发生在控制台程序端。默认情况下,如果已知要重定向,stdout将被完全缓冲:

如果已知stdout不是指交互式设备,则流被完全缓冲。否则,默认情况下,流是行缓冲的还是未缓冲的取决于库(请参见setvbuf)。源

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