2008-09-15 6 views
18

나는 닷넷 프레임 워크 3.5마지막 OutputDataReceived가 언제 도착했는지 어떻게 알 수 있습니까?

내가 모두 StandardOutputStandardError 파이프를 리디렉션하고 난 비동기 그들로부터 데이터를 수신하고 있습니다 대상으로 프로그램에서 System.Diagnostics.Process가 객체가 있습니다. 또한 Exited 이벤트에 대한 이벤트 처리기를 설정했습니다.

일단 내가 Process.Start()으로 전화를하면 이벤트가 발생하기를 기다리는 동안 다른 일을하고 싶습니다.

불행히도 많은 양의 정보를 반환하는 프로세스의 경우 Expected 이벤트는 마지막 OutputDataReceived 이벤트 전에 발생하는 것으로 보입니다.

마지막으로 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); 
    } 


    } 
} 

당신이 "에 Exited (이벤트)"출력 내에서 완전히 변수 위치에 나타납니다 것을 볼이 프로그램을 실행할 수 있습니다. 몇 번 실행해야 할 수도 있습니다. 분명히 "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(); 
} 
관련 문제