C# 在 .NET 中有效地重定向标准输出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/164736/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Redirect Standard Output Efficiently in .NET
提问by Vincent
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.
我正在尝试从 .NET 程序调用 php-cgi.exe。我使用 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()
采纳答案by Bob King
You can use the OutputDataReceived eventto receive data as it's pumped to StdOut.
您可以使用OutputDataReceived 事件在数据被泵送到 StdOut 时接收数据。
回答by Jader Dias
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);
}
}
回答by Martin.Martinsson
The problem is due a bad php.ini config. I had the same problem and i downloaded the Windows installer from: http://windows.php.net/download/.
问题是由于错误的 php.ini 配置。我遇到了同样的问题,我从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à Speedy Gonzales,每秒转换 20 php。
You can safely use "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.
您可以安全地使用“oProcess.StandardOutput.ReadToEnd()”。它的可读性和速度几乎与使用线程解决方案一样快。要将线程解决方案与字符串结合使用,您需要引入一个事件或其他东西。
Cheers
干杯