我正在使用在后台运行cmd的winform,异步地重定向输入和输出。等待命令完成
目前,winform迭代了一系列命令,通过StreamInter将StandardInput重定向到的每个cmd写入cmd。在写入下一行之前,如何强制循环等待当前命令在cmd中完成?
编辑:我拿出了我所有的实际项目代码,并用它替换了它,这是我试图做的简化版本,只包括我的项目中与我的问题相关的组件。
public partial class Form1 : Form
{
public delegate void WriteToConsoleMethod(string text);
Process _process;
string[] _commands =
{
"echo hello world",
"echo my name is T.K.",
"echo Here is a list of commands"
};
public Form1()
{
InitializeComponent();
ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd")
{
RedirectStandardError = true,
RedirectStandardInput = true,
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true
};
_process = Process.Start(processStartInfo);
_process.OutputDataReceived += new DataReceivedEventHandler(new DataReceivedEventHandler(DataReceived_EventHandler));
_process.ErrorDataReceived += new DataReceivedEventHandler(new DataReceivedEventHandler(DataReceived_EventHandler));
_process.BeginErrorReadLine();
_process.BeginOutputReadLine();
}
private void DataReceived_EventHandler(object sender, DataReceivedEventArgs e)
{
IAsyncResult result = this.BeginInvoke(new WriteToConsoleMethod(writeToConsole), new object[] { e.Data + Environment.NewLine });
this.EndInvoke(result);
}
private void writeToConsole(string output)
{
txtbxConsole.AppendText(output);
}
private void btnBegin_Click(object sender, EventArgs e)
{
foreach (string command in _commands)
{
_process.StandardInput.WriteLine(command);
// I want a way to pause here until the cmd has finished processing the command.
}
}
}
你能发表一些代码吗? – JohnFx 2011-02-23 13:56:15
好的 - 给我一分钟把它放在一起。 – 2011-02-23 14:07:23
你可以发布run方法的代码吗? – sgmoore 2011-02-23 14:15:56