Redirect Standard Output Efficiently in .NET

前端 未结 3 1270
旧时难觅i
旧时难觅i 2020-12-03 12:09

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 an

3条回答
  •  遥遥无期
    2020-12-03 12:59

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

提交回复
热议问题