等待命令在C#中完成

Nav*_*een 10 c#

我是C#的新手,并尝试开发一个小型应用程序,在内部打开命令提示符并在此处执行一些命令.这是我到目前为止所做的:

    m_command = new Process();
    m_command.StartInfo.FileName = @"cmd.exe";
    m_command.StartInfo.UseShellExecute = false;
    m_command.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    m_command.StartInfo.CreateNoWindow = true;
    m_command.StartInfo.RedirectStandardInput = true;
    m_command.StartInfo.RedirectStandardOutput = true;

    m_command.Start();

    m_reader = m_command.StandardOutput;
    m_writer = m_command.StandardInput;

    m_writer.WriteLine("Somecommand"); //execute some command
Run Code Online (Sandbox Code Playgroud)

如您所见,我已重定向输入和输出.我的问题是如何同步执行"some命令",即我想使用重定向输出读取命令的结果.为此,我必须等到我使用WriteLine调用的命令才能完成.我怎么做?

Jon*_*eet 15

这实际上取决于命令的作用.您可以等待进程退出Process.WaitForExit,同时从m_reader另一个线程中读取或使用OutputDataReceived.只有在命令完成后进程退出时,这才有效.(注意,您必须读取输出,否则它可能会填满输出缓冲区并基本上阻止该过程.)

另一个选项是,如果在命令完成后您将获得一定的输出 - 例如下一个命令提示符.麻烦的是,如果你的命令碰巧输出同样的东西,你就会弄错.

感觉就像启动这样的命令提示符不是一个很好的方法.您是否每次都没有创建单独的流程?

另一个选择:如果你可以通过命令行计算你刚刚启动的进程,你可以找到它作为a Process并等待退出.虽然这很棘手 - 我真的会尝试重新设计你的解决方案.


Phi*_*ert 9

你可以打电话

 m_command.WaitForExit();
Run Code Online (Sandbox Code Playgroud)


ale*_*lex 8

这是我在一个小项目中使用的:

processStartInfo startInfo = new ProcessStartInfo();
    startInfo.CreateNoWindow = true;
    startInfo.UseShellExecute = false;
    startInfo.WindowStyle = ProcessWindowStyle.Hidden;
    startInfo.FileName = "cmd.exe";
    startInfo.Arguments = command;

// Start the process with the info we specified.
    // Call WaitForExit and then the using statement will close.
    using(Process exeProcess = Process.Start(startInfo))
    {
        exeProcess.WaitForExit();
    }
Run Code Online (Sandbox Code Playgroud)