簡體   English   中英

同步讀取進程的標准輸出

[英]Synchronously reading stdout of a process

我正在執行一個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);

      }

嘗試一下, 此示例寬松地改編了此示例

    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線程上進行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM