简体   繁体   English

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

[英]Redirect Standard Output Efficiently in .NET

I am trying to call php-cgi.exe from a .NET program. 我试图从.NET程序调用php-cgi.exe。 I use RedirectStandardOutput to get the output back as a stream but the whole thing is very slow. 我使用RedirectStandardOutput将输出作为流返回,但整个过程非常慢。

Do you have any idea on how I can make that faster? 你对我如何能加快速度有任何想法吗? Any other technique? 还有其他技术吗?

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

The best solution I have found is: 我发现的最佳解决方案是:

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

您可以使用OutputDataReceived事件接收数据,因为它被泵送到StdOut。

The problem is due a bad php.ini config. 问题是由于php.ini配置错误。 I had the same problem and i downloaded the Windows installer from: http://windows.php.net/download/ . 我有同样的问题,我从http://windows.php.net/download/下载了Windows安装程序。

After that and commenting out not needed extensions, the conversion process is alà Speedy Gonzales, converting 20 php per second. 在那之后并评论出不需要的扩展,转换过程是alàSpeedyGonzales,每秒转换20个PHP。

You can safely use "oProcess.StandardOutput.ReadToEnd()". 您可以安全地使用“oProcess.StandardOutput.ReadToEnd()”。 It's more readable and alomost as fast as using the thread solution. 它比使用线程解决方案更快,更快速,更快速。 To use the thread solution in conjunction with a string you need to introduce an event or something. 要将线程解决方案与字符串结合使用,您需要引入事件或其他内容。

Cheers 干杯

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM