Periodically check command line output in C#
In my C# program I call an external progr开发者_如何学编程am from command line using a process and redirecting the standard input. After I issue the command to the external program, every 3 seconds I have to issue another command to check the status - the program will respond with InProgress or Finished. I would like some help in doing this as efficient as possible. The process checks the status of a long running operation executed by a windows service (for reasons I would not like to detail I cannot interact directly with the service), therefore after each command the process exits, but the exitcode is always the same no matter the outcome.
use Process.Exited event and Process.ExitCode property
For examples:
http://msdn.microsoft.com/en-us/library/system.diagnostics.process.exited.aspx
http://msdn.microsoft.com/en-us/library/system.diagnostics.process.exitcode.aspx
You can use a Timer to execute some code at a specified interval, and Process.StandardOutput to read the output of the process:
Timer timer = new Timer(_ =>
{
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "foobar.exe";
p.Start();
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
switch (output)
{
case "InProgress":
// ...
break;
case "Finished":
// ...
break;
}
});
timer.Change(TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(3));
精彩评论