简体   繁体   中英

Periodically check command line output in C#

In my C# program I call an external program 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.

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM