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

标签 c# .net asynchronous process

我正在使用 .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/

相关文章:

c# - EF 4,如何添加部分类

c# - .NET 反编译器区分 "using"和 "try...finally"

javascript - 链接多个可选异步 Ajax 请求

ios - 我怎样才能提高实现照片过滤器的速度?

c# - 通过 .NET (C#) 发布 Google Plus

c# - 将 (V)C++ long* 转换为 C# Int32* 的安全方法?

c# - 可以为这个表达式求值器类的私有(private)方法编写单元测试吗?

c# - 如何在测试方法中模拟按键?

c# - Lambda 不能做 Int16 比较?

node.js - Node.js 如何同时异步和单线程?