简体   繁体   English

运行命令并等待c#中的完成

[英]Run commands and wait for completion in c#

I need to do this in my c# program. 我需要在我的c#程序中执行此操作。

           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. 我的命令正确执行,但问题是Parse日志代码不等待cmd1和cmd2执行完成。 I cannot call exit and process. 我不能打电话给退出和处理。 waitforexit because, after parsing the logs, I have more commands to execute. waitforexit因为在解析日志后,我有更多的命令要执行。

Here is how process start info is set. 以下是如何设置流程启动信息。 LaunchCommandWindow() 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? 如何获取解析日志代码以等待cmd2完成?

Thanks. 谢谢。

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

Create a new thread to run the tasks. 创建一个新线程来运行任务。

Use a BackgroundWorker . 使用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. 经过进一步的研究,以下是对其余部分的思考:如果要读取输出,则必须将RedirectStandardOutput设置为true。

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. 如果你没有运行在同一窗口中两个命令,你可以调用process.WaitForExit(int)其中int是等待的毫秒数,然后启动一个新的进程(或process与新参数)火CMD2 。

I think Process.WaitForExit() method is just what you need. 我认为Process.WaitForExit()方法正是您所需要的。 There is also Process.HasExited property. 还有Process.HasExited属性。
And for launching use something like that "cmd /C cmd1 & cmd2" 对于启动使用类似“cmd / C cmd1&cmd2”的东西

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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