[英]Periodically check command line output in C#
在我的C#程序中,我使用進程從命令行調用外部程序並重定向標准輸入。 在向外部程序發出命令后,每3秒鍾我必須發出另一個命令來檢查狀態 - 程序將以InProgress或Finished響應。 我希望盡可能高效地做到這一點。 該過程檢查由Windows服務執行的長時間運行操作的狀態(由於我不想詳細說明我不能直接與服務交互的原因),因此在每個命令之后進程退出,但exitcode始終是相同的,無論如何結果。
使用Process.Exited事件和Process.ExitCode屬性
舉些例子:
http://msdn.microsoft.com/en-us/library/system.diagnostics.process.exited.aspx
http://msdn.microsoft.com/en-us/library/system.diagnostics.process.exitcode.aspx
您可以使用Timer以指定的時間間隔執行某些代碼,並使用Process.StandardOutput來讀取進程的輸出:
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));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.