【问题标题】:Synchronously reading stdout of a process同步读取进程的标准输出
【发布时间】:2016-03-29 11:40:52
【问题描述】:

我正在执行一个 exe 文件,其中包含我的 c# winform 中的一些 c 代码,但只有在完全执行 exe 后才能获得 c 代码的完整输出。我希望 exe 将其输出同步传递到我的 winform(实时逐行)。

    var proc = new Process
      {
          StartInfo = new ProcessStartInfo
          {
              FileName = "background.exe",
              Arguments = command,
              UseShellExecute = false,
              RedirectStandardOutput = true,
              CreateNoWindow = true
          }
      };


      proc.Start();
      while (!proc.StandardOutput.EndOfStream)
      {
          ConsoleWindow.AppendText(proc.StandardOutput.ReadLine());
          ConsoleWindow.AppendText(Environment.NewLine);

      }

【问题讨论】:

  • some c code 是什么意思?除非正在执行的 process 将其放在那里,否则不会将文本写入输出。你应该检查background.exe的代码。并确保background.exe 实际上是一个已编译的二进制可执行文件,而不仅仅是具有不同扩展名的 C 文件
  • 你检查过这个question和这个question吗?
  • 检查了所有的代码示例,他们只有在过程完成后才读取输出。

标签: c# .net winforms process


【解决方案1】:

试试这个,大致改编自this example

    private void button1_Click(object sender, EventArgs e)
    {
        var consoleProcess = new Process
        {
            StartInfo =
            {
                FileName =
                    @"background.exe",
                UseShellExecute = false,
                RedirectStandardOutput = true
            }
        };

        consoleProcess.OutputDataReceived += ConsoleOutputHandler;
        consoleProcess.StartInfo.RedirectStandardInput = true;
        consoleProcess.Start();
        consoleProcess.BeginOutputReadLine();
    }

    private void ConsoleOutputHandler(object sendingProcess,
        DataReceivedEventArgs outLine)
    {
        // This is the method in your form that's 
        // going to display the line of output from the console.
        WriteToOutput(outLine.Data);
    }

请注意,从控制台接收输出的事件处理程序在不同的线程上执行,因此您必须确保用于在表单上显示输出的任何内容都发生在 UI 线程上。

【讨论】:

  • BeginOutputReadLine 不是异步方法吗?
  • @Sipo 可能是。这是两年前的事了,我什么都不记得了。我很可能会删除答案。
猜你喜欢
  • 1970-01-01
  • 2011-02-17
  • 2015-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-21
相关资源
最近更新 更多