code_junkie

C# :How do I know when the last OutputDataReceived has arrived

Nov 10th, 2011
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.68 KB | None | 0 0
  1. using System;
  2. using System.Diagnostics;
  3. using System.Threading;
  4.  
  5. namespace ConsoleApplication1
  6. {
  7. class Program
  8. {
  9.  
  10. static void Main(string[] args)
  11. {
  12. string command = "output.exe";
  13. string arguments = " whatever";
  14.  
  15. ProcessStartInfo info = new ProcessStartInfo(command, arguments);
  16.  
  17. // Redirect the standard output of the process.
  18. info.RedirectStandardOutput = true;
  19. info.RedirectStandardError = true;
  20.  
  21. // Set UseShellExecute to false for redirection
  22. info.UseShellExecute = false;
  23.  
  24. Process proc = new Process();
  25. proc.StartInfo = info;
  26. proc.EnableRaisingEvents = true;
  27.  
  28. // Set our event handler to asynchronously read the sort output.
  29. proc.OutputDataReceived += new DataReceivedEventHandler(proc_OutputDataReceived);
  30. proc.ErrorDataReceived += new DataReceivedEventHandler(proc_ErrorDataReceived);
  31. proc.Exited += new EventHandler(proc_Exited);
  32.  
  33. proc.Start();
  34. // Start the asynchronous read of the sort output stream. Note this line!
  35. proc.BeginOutputReadLine();
  36. proc.BeginErrorReadLine();
  37.  
  38. proc.WaitForExit();
  39.  
  40. Console.WriteLine("Exited (Main)");
  41.  
  42. }
  43.  
  44. static void proc_Exited(object sender, EventArgs e)
  45. {
  46.  
  47. Console.WriteLine("Exited (Event)");
  48. }
  49.  
  50.  
  51.  
  52. static void proc_ErrorDataReceived(object sender, DataReceivedEventArgs e)
  53. {
  54. Console.WriteLine("Error: {0}", e.Data);
  55. }
  56.  
  57.  
  58.  
  59. static void proc_OutputDataReceived(object sender, DataReceivedEventArgs e)
  60. {
  61. Console.WriteLine("Output data: {0}", e.Data);
  62. }
  63.  
  64.  
  65. }
  66. }
  67.  
  68. static void proc_ErrorDataReceived(object sender, DataReceivedEventArgs e)
  69. {
  70. if( e.Data == null ) _exited.Set();
  71. }
Add Comment
Please, Sign In to add comment