簡體   English   中英

等待命令在C#中完成

[英]Waiting for the command to complete in 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

如您所見,我已重定向輸入和輸出。 我的問題是如何同步執行“some命令”,即我想使用重定向輸出讀取命令的結果。 為此,我必須等到我使用WriteLine調用的命令才能完成。 我怎么做?

這實際上取決於命令的作用。 您可以等待進程退出Process.WaitForExit ,同時從另一個線程中的m_reader或使用OutputDataReceived讀取。 只有在命令完成后進程退出時,這才有效。 (注意,您必須讀取輸出,否則它可能會填滿輸出緩沖區並基本上阻止該過程。)

另一個選項是,如果在命令完成后您將獲得一定的輸出 - 例如下一個命令提示符。 麻煩的是,如果你的命令碰巧輸出同樣的東西,你就會弄錯。

感覺就像啟動這樣的命令提示符不是一個很好的方法。 您是否每次都沒有創建單獨的流程?

另一種選擇:如果你可以計算出你剛剛通過命令行推出什么樣的過程,你會發現,作為一個Process ,並等待退出。 雖然這很棘手 - 我真的會嘗試重新設計你的解決方案。

你可以打電話

 m_command.WaitForExit();

這是我在一個小項目中使用的:

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

最簡單的方法是將所有命令放入.cmd文件,執行並使用

 Process.Start("cmdfile").WaitForExit();

您可以在輸出中等待提示。

非常棘手。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM