繁体   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