C # чтение stdout дочернего процесса асинхронно

Я работаю с C # и не могу понять, как читатьстандартный вывод асинхронно от дочернего процесса. Я хочу создать дочерний процесс, который выполняет приложение, а затем представить все, что получено от stdout этого процесса, в текстовом поле. Мне нужно увидеть каждый выходной символ дочернего процесса немедленно и не могу дождаться завершения строки, поэтому я не думаю, чтоProcess.OutputDataReceived событие соответствует моей цели. Можете ли вы сказать мне разумный способ сделать это?

Я пробовал звонитьProcess.StandardOutput.BaseStream.BeginRead() и передать ему функцию обратного вызова, но в этой функции обратного вызова я получаю исключение отProcess.StandardOutput.BaseStream.EndRead().

Мой код выглядит следующим образом (дочерний процесс представляет собой механизм сценариев - сокращенно «SE» - для проверки функциональности внешнего устройства. Сценарии выполняются последовательно, и для каждого сценария требуется один экземпляр приложения SE)

private bool startScript()
{
  // Starts the currently indexed script

  if (null != scriptList)
  {

    if (0 == scriptList.Count || scriptListIndexer == scriptList.Count)
    {
      // If indexer equals list count then there are no active scripts in
      // the list or the last active script in the list has just finished
      return false;                              // ## RETURN ##
    }
    if (ScriptExecutionState.RUNNING == scriptList[scriptListIndexer].executionState)
    {
      return false;                              // ## RETURN ##
    }

    if (0 == SE_Path.Length)
    {
      return false;                              // ## RETURN ##
    }

    SE_Process = new Process();
    SE_Process.StartInfo.FileName = SE_Path;
    SE_Process.StartInfo.CreateNoWindow = true;
    SE_Process.StartInfo.UseShellExecute = false;
    SE_Process.StartInfo.RedirectStandardError = true;
    SE_Process.StartInfo.RedirectStandardOutput = true;
    SE_Process.EnableRaisingEvents = true;
    SE_Process.StartInfo.Arguments = scriptList[scriptListIndexer].getParameterString();

    // Subscribe to process exit event
    SE_Process.Exited += new EventHandler(SE_Process_Exited);

    try
    {
      if (SE_Process.Start())
      {
        // Do stuff
      }
      else
      {
        // Do stuff
      }
    }
    catch (Exception exc)
    {
      // Do stuff
    }

    // Assign 'read_SE_StdOut()' as call-back for the event of stdout-data from SE
    SE_Process.StandardOutput.BaseStream.BeginRead(SE_StdOutBuffer, 0, SE_BUFFERSIZE, read_SE_StdOut, null);

    return true;                                       // ## RETURN ##

  }
  else
  {
    return false;                                      // ## RETURN ##
  }
}

private void read_SE_StdOut(IAsyncResult result)
{
  try
  {
    int bytesRead = SE_Process.StandardOutput.BaseStream.EndRead(result);  // <-- Throws exceptions

    if (0 != bytesRead)
    {
      // Write the received data in output textbox
      ...
    }

    // Reset the callback
    SE_Process.StandardOutput.BaseStream.BeginRead(SE_StdOutBuffer, 0, SE_BUFFERSIZE,     read_SE_StdOut, null);
  }
  catch (Exception exc)
  {
    // Do stuff
  }
}

void SE_Process_Exited(object sender, EventArgs e)
{

  // Keep track of whether or not the next script shall be started
  bool continueSession = false;

  switch (SE_Process.ExitCode)
  {
    case 0: // PASS
    {
      // Do stuff
    }

    ...

  }

  SE_Process.Dispose(); // TODO: Is it necessary to dispose of the process?

  if (continueSession)
  {
    ts_incrementScriptListIndexer();

    if (scriptListIndexer == scriptList.Count)
    {
      // Last script has finished, reset the indexer and re-enable
      // 'scriptListView'
      ...
    }
    else
    {
      if (!startScript())
      {
        // Do stuff
      }
    }
  }
  else
  {
    ts_resetScriptListIndexer();
    threadSafeEnableScriptListView();
  }
}

Что происходит, когда после завершения одного процесса SE я получаю исключение типаInvalidOperationException это говорит

StandardOut не был перенаправлен или процесс еще не начался.

от звонка доSE_Process.StandardOutput.BaseStream.EndRead(), Я не понимаю почему, потому что я установилSE_Process.StartInfo.RedirectStandardOutput перед началом каждого нового процесса. Мне кажется, что поток stdout завершенного процесса вызывает мойread_SE_StdOut() функция после завершения процесса, это возможно?

Спасибо за чтение!

Ответы на вопрос(1)

Ваш ответ на вопрос