gpt4 book ai didi

c# - 异步读取进程输出时的延迟

转载 作者:行者123 更新时间:2023-11-30 21:16:27 27 4
gpt4 key购买 nike

我正在使用 .NET 和 C# 启动一个进程并异步读取它的输出。我的问题是在我的程序读取输出之前似乎有延迟。如果我在命令行上运行可执行文件,它开始运行时会立即有输出。但是当我使用我的代码运行它时,ReadOutput 事件处理程序直到进程退出才被调用。我想使用它来提供进程输出的实时 View ,所以我不想等待(几分钟)直到进程退出。

这里是一些相关的代码:

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

关于c# - 异步读取进程输出时的延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5187568/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com