簡體   English   中英

定期檢查C#中的命令行輸出

[英]Periodically check command line output in C#

在我的C#程序中,我使用進程從命令行調用外部程序並重定向標准輸入。 在向外部程序發出命令后,每3秒鍾我必須發出另一個命令來檢查狀態 - 程序將以InProgress或Finished響應。 我希望盡可能高效地做到這一點。 該過程檢查由Windows服務執行的長時間運行操作的狀態(由於我不想詳細說明我不能直接與服務交互的原因),因此在每個命令之后進程退出,但exitcode始終是相同的,無論如何結果。

您可以使用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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM