简体   繁体   中英

Run commands and wait for completion in c#

I need to do this in my c# program.

           Process process = LaunchCommandWindow("Special args and environment set")
           process.StandardInput.WriteLine("cmd1");
           process.StandardInput.WriteLine("cmd2");

           //Parse logs
            using (Streamreader sr =  new ())
           { etc etc..}

My commands execute correctly, but the problem is that Parse logs code doesnt wait for cmd1 and cmd2 execution to complete. I cannot call exit and process. waitforexit because, after parsing the logs, I have more commands to execute.

Here is how process start info is set. LaunchCommandWindow()

         ProcessStartInfo startInfo = new ProcessStartInfo();

        startInfo.FileName = Path.Combine(Environment.SystemDirectory, "cmd.exe");
        startInfo.Arguments = "/K " + newEnvironmentArgs;

        startInfo.UseShellExecute = false; 
        startInfo.RedirectStandardInput = true;
        Process process = new Process();
        process.StartInfo = startInfo;
        process.Start();

        return process;

How do I get the parse logs code to wait for cmd2 completion?

Thanks.

如果“cmd2”将完成写入标准输出流,您可以监听标准输出,直到看到该事件,然后从那里进行处理。

Create a new thread to run the tasks.

Use a BackgroundWorker .

When it finishes, it raises an event (in your main thread) from which you can continue running.

This will prevent your program from hanging, and if there is other work to be done, it can allow you to do it while the other thread runs.

Here's a tutorial

-----Edit-----

After further research, here's a thought for the rest: You do have to set RedirectStandardOutput to true, if you want to read the output.

If you don't have to run both commands in the same window, you can call process.WaitForExit(int) where the int is the number of milliseconds to wait, then launch a new process (or process with new arguments) to fire cmd2.

I think Process.WaitForExit() method is just what you need. There is also Process.HasExited property.
And for launching use something like that "cmd /C cmd1 & cmd2"

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