C#处理标准输出延迟

时间:2015-07-01 04:51:47

标签: c# forms process buffer stdout

在C#表单中,我正在运行process,其启动信息类似于Redirect console output to textbox in separate programC# get process output while running,但该过程运行正常,但输出需要很长时间才能显示在{{ 3}}。

我想在流程生成后立即看到该文本;根据{{​​3}}(第一条评论)我需要等到事件被触发之前填充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;并显示命令窗口。

1 个答案:

答案 0 :(得分:4)

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

  

如果已知stdout未引用交互式设备,则该流完全缓冲。否则,它依赖于库依赖于流是行缓冲还是未缓冲(参见setvbuf)。 Source

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

相关问题