tags:

views:

1192

answers:

3

I am trying to call php-cgi.exe from a .NET program. I use RedirectStandardOutput to get the output back as a stream but the whole thing is very slow.

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()
+1  A: 

What part exactly is slow? We use redirected streams on processes all the time and haven't seen any observable slowdowns. Perhaps your PHP script is running slowly. Some timing information would be helpful in this instance.

sixlettervariables
+4  A: 

You can use the OutputDataReceived event to receive data as it's pumped to StdOut.

Bob King
Just a side note, I would redirect standard error with the OutputDataReceived event as well. You could then throw a new exception or handle the error in another way.
Tom Alderman
Excellent Point!
Bob King
@Vincent @Bob King The problem with this event is that it only is called when a the output receives a newline. My solution in another answer in this thread works also when the output has no carriage returns nor newlines.
Jader Dias
+2  A: 

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);
    }
}
Jader Dias
you're right, this solution is resellient but it's importance is not clear until you go through the problem you described in the comment on the question
Ahmed Khalaf