【问题标题】:How to read from (redirected stdout) StreamReader without blocking?如何在不阻塞的情况下从(重定向的标准输出)StreamReader 读取?
【发布时间】:2018-08-15 15:41:02
【问题描述】:

我想用 C# 做的是:

  1. 将已编译的 C++ 程序作为子进程启动,读取其重定向的标准输出。
  2. 将读取的字节输出到另一个文件,而 stdout 由子进程附加。
  3. 如果子进程在 10 秒后没有退出,则终止子进程。
  4. 如果子进程产生的输出大于 64MB,则终止子进程。

我正在使用 while 循环来检查子进程的执行时间,但是当我尝试从 Process.StandardOutput 获取输出数据时,线程将被阻塞,并且超时检查循环在子进程结束之前将无法工作.

有什么方法可以在 StreamReader 上进行非阻塞读取,或者在不使用非阻塞读取的情况下具有相同效果的解决方法?

【问题讨论】:

    标签: c# subprocess streamreader


    【解决方案1】:

    您是否使用 Process 类来启动 C++ 程序?

    如果是这样,您可以read asynchronously the output 与事件。

    来自 msdn 的示例:

    private static int lineCount = 0;
    private static StringBuilder output = new StringBuilder();
    
    public static void Main()
    {
        Process process = new Process();
        process.StartInfo.FileName = "ipconfig.exe";
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.RedirectStandardOutput = true;
        process.OutputDataReceived += new DataReceivedEventHandler((sender, e) =>
        {
            // Prepend line numbers to each line of the output.
            if (!String.IsNullOrEmpty(e.Data))
            {
                lineCount++;
                output.Append("\n[" + lineCount + "]: " + e.Data);
            }
        });
    
        process.Start();
    
        // Asynchronously read the standard output of the spawned process. 
        // This raises OutputDataReceived events for each line of output.
        process.BeginOutputReadLine();
        process.WaitForExit();
    
        // Write the redirected output to this application's window.
        Console.WriteLine(output);
    
        process.WaitForExit();
        process.Close();
    
        Console.WriteLine("\n\nPress any key to exit.");
        Console.ReadLine();
    }
    

    【讨论】:

    • 是的,我正在使用 Process。这适用于它的设计目的,但还有两个问题:(1)如何通知或等待异步读取退出? process.HasExited 会管理这个吗? (2) 这看起来只适用于读取行,但标准输出可能包含大于 64MB 的行。
    • 好吧,我在您给定的链接中找到了(1)的答案...算了吧...
    猜你喜欢
    • 2020-08-06
    • 1970-01-01
    • 2018-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-01
    • 1970-01-01
    • 2023-01-05
    相关资源
    最近更新 更多