2008-09-15 13 views
18

私は、.NET Framework 3.5最後のOutputDataReceivedがいつ到着したかはどのように知ることができますか?

を対象プログラムに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); 
    } 


    } 
} 

このプログラムを実行しているあなたは「終了しました(イベント)」出力内の完全に可変の場所に表示されていることがわかります。数回実行する必要があるかもしれません。明らかに、適切に大量の出力を生成する任意のプログラムで "output.exe"を置き換える必要があります。

質問:再度最後のOutputDataReceivedが届いた時期を知るにはどうすればよいですか?理想的には、Exitedイベントを受信した最後のイベントにします。

答えて

23

これに対する答えはそのe.Data will be set to null次のとおりです。

static void proc_ErrorDataReceived(object sender, DataReceivedEventArgs e) 
{ 
    if(e.Data == null) _exited.Set(); 
} 
関連する問題