我怎么知道最后一次OutputDataReceived何时到达?

21 c# asynchronous system.diagnostics

我在针对.Net framework 3.5的程序中有一个System.Diagnostics.Process对象

我已经重定向了两个StandardOutputStandardError管道,我正在异步地从它们接收数据.我还为Exited事件设置了一个事件处理程序.

一旦我打电话,Process.Start()我想在等待事件被提出的时候去做其他工作.

不幸的是,对于返回大量信息的进程,似乎在最后一个OutputDataReceived事件之前触发了Exited 事件.

我怎么知道OutputDataReceived收到最后一次的时间?理想情况下,我希望这次Exited活动成为我收到的最后一次活动.

这是一个示例程序:

using System;
using System.Diagnostics;
using System.Threading;

namespace ConsoleApplication1
{
  class Program
  {

    static void Main(string[] args)
    {
      string command = "output.exe";
      string arguments = " whatever";

      ProcessStartInfo info = new ProcessStartInfo(command, arguments);

      // Redirect the standard output of the process. 
      info.RedirectStandardOutput = true;
      info.RedirectStandardError = true;

      // Set UseShellExecute to false for redirection
      info.UseShellExecute = false;

      Process proc = new Process();
      proc.StartInfo = info;
      proc.EnableRaisingEvents = true;

      // Set our event handler to asynchronously read the sort output.
      proc.OutputDataReceived += new DataReceivedEventHandler(proc_OutputDataReceived);
      proc.ErrorDataReceived += new DataReceivedEventHandler(proc_ErrorDataReceived);
      proc.Exited += new EventHandler(proc_Exited);

      proc.Start();
      // Start the asynchronous read of the sort output stream. Note this line!
      proc.BeginOutputReadLine();
      proc.BeginErrorReadLine();

      proc.WaitForExit();

      Console.WriteLine("Exited (Main)");

    }

    static void proc_Exited(object sender, EventArgs e)
    {

      Console.WriteLine("Exited (Event)");
    }



    static void proc_ErrorDataReceived(object sender, DataReceivedEventArgs e)
    {
      Console.WriteLine("Error: {0}", e.Data);
    }



    static void proc_OutputDataReceived(object sender, DataReceivedEventArgs e)
    {
      Console.WriteLine("Output data: {0}", e.Data);
    }


  }
}
Run Code Online (Sandbox Code Playgroud)

运行此程序时,您会注意到"退出(事件)"出现在输出中的完全可变位置.您可能需要运行几次,显然,您需要将"output.exe"替换为您选择的产生适当大量输出的程序.

那么,问题又是:我怎么知道最后一次OutputDataReceived收到的?理想情况下,我希望这次Exited活动成为我收到的最后一次活动.

csh*_*net 27

答案是:e.Data将设置为null:

static void proc_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
     if( e.Data == null ) _exited.Set();
}
Run Code Online (Sandbox Code Playgroud)