在.NET中有效地重定向标准输出

时间:2020-03-06 15:03:07  来源:igfitidea点击:

我正在尝试从.NET程序调用php-cgi.exe。我使用RedirectStandardOutput将输出作为流返回,但整个过程非常缓慢。

我们是否知道我可以如何更快地做到这一点?还有其他技巧吗?

Dim oCGI As ProcessStartInfo = New ProcessStartInfo()
    oCGI.WorkingDirectory = "C:\Program Files\Application\php"
    oCGI.FileName = "php-cgi.exe"
    oCGI.RedirectStandardOutput = True
    oCGI.RedirectStandardInput = True
    oCGI.UseShellExecute = False
    oCGI.CreateNoWindow = True

    Dim oProcess As Process = New Process()

    oProcess.StartInfo = oCGI
    oProcess.Start()

    oProcess.StandardOutput.ReadToEnd()

解决方案

我们可以使用OutputDataReceived事件来接收泵送至StdOut的数据。

我发现的最佳解决方案是:

private void Redirect(StreamReader input, TextBox output)
{
    new Thread(a =>
    {
        var buffer = new char[1];
        while (input.Read(buffer, 0, 1) > 0)
        {
            output.Dispatcher.Invoke(new Action(delegate
            {
                output.Text += new string(buffer);
            }));
        };
    }).Start();
}

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    process = new Process
    {
        StartInfo = new ProcessStartInfo
        {
            CreateNoWindow = true,
            FileName = "php-cgi.exe",
            RedirectStandardOutput = true,
            UseShellExecute = false,
            WorkingDirectory = @"C:\Program Files\Application\php",
        }
    };
    if (process.Start())
    {
        Redirect(process.StandardOutput, textBox1);
    }
}

问题是由于错误的php.ini配置。我遇到了同样的问题,我从http://windows.php.net/download/下载了Windows安装程序。

之后,注释掉不需要的扩展,转换过程就是Speedy Gonzales,每秒转换20 PHP。

我们可以安全地使用" oProcess.StandardOutput.ReadToEnd()"。它比使用线程解决方案更具可读性和最快的速度。要将线程解决方案与字符串结合使用,我们需要引入一个事件或者某些东西。

干杯