我正在使用 .NET 和 C# 启动一个进程并异步读取它的输出。我的问题是,在我的程序读取输出之前似乎存在延迟。如果我在命令行上运行可执行文件,则在它开始运行时立即有输出。但是,当我使用代码运行它时,在进程退出之前不会调用 ReadOutput 事件处理程序。我想用它来提供进程输出的实时视图,所以我不想等待(几分钟)直到进程退出。
这是一些相关代码:
MyProcess = new Process();
MyProcess.StartInfo.FileName = command;
MyProcess.StartInfo.Arguments = args;
MyProcess.StartInfo.UseShellExecute = false;
MyProcess.StartInfo.RedirectStandardOutput = true;
MyProcess.StartInfo.RedirectStandardError = true;
MyProcess.StartInfo.RedirectStandardInput = true;
MyProcess.OutputDataReceived += new DataReceivedEventHandler(ReadOutput);
MyProcess.ErrorDataReceived += new DataReceivedEventHandler(ReadOutput);
if (!MyProcess.Start())
{
throw new Exception("Process could not be started");
}
try
{
MyProcess.BeginOutputReadLine();
MyProcess.BeginErrorReadLine();
}
catch (Exception ex)
{
throw new Exception("Unable to begin asynchronous reading from process";
}
这是我的事件处理程序:
private void ReadOutput(object sendingProcess, DataReceivedEventArgs outLine)
{
OutputBuilder.AppendLine(outLine.Data);
Console.WriteLine(outLine.Data);
Console.Out.Flush();
}
这是我根据我的评论使用 lambda 语法执行此操作的方式 (C# 3)。
/// <summary>
/// Collects standard output text from the launched program.
/// </summary>
private static readonly StringBuilder outputText = new StringBuilder();
/// <summary>
/// Collects standard error text from the launched program.
/// </summary>
private static readonly StringBuilder errorText = new StringBuilder();
/// <summary>
/// The program's entry point.
/// </summary>
/// <param name="args">The command-line arguments.</param>
/// <returns>The exit code.</returns>
private static int Main(string[] args)
{
using (var process = Process.Start(new ProcessStartInfo(
"program.exe",
args)
{
CreateNoWindow = true,
ErrorDialog = false,
RedirectStandardError = true,
RedirectStandardOutput = true,
UseShellExecute = false
}))
{
process.OutputDataReceived += (sendingProcess, outLine) =>
outputText.AppendLine(outLine.Data);
process.ErrorDataReceived += (sendingProcess, errorLine) =>
errorText.AppendLine(errorLine.Data);
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
Console.WriteLine(errorText.ToString());
Console.WriteLine(outputText.ToString());
return process.ExitCode;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)