1

我试图用 C# 做的是:

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

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

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

4

1 回答 1

1

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

如果是这样,您可以使用事件异步读取输出。

来自 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();
}
于 2018-08-15T16:07:44.783 回答