使用Process执行DOS命令异步输出不及时
以下代码是使用Process执行DOS命令异步输出,cmdProcess_OutputDataReceived中能够获取DOS信息,一行一行的获取,但是,需要在DOS命令执行完成后,cmdProcess_OutputDataReceived才会调用,现在就是需要在界面上及时显示DOS的执行情况和反馈信息,能够一有输出就获取,并在界面上显示。望大侠指教,先谢过~~~!!!
public void ExecuteDOS(string command, int seconds)
{
//string output = ""; // 输出字符串
if (command!=null&&!command.Equals(""))
{
Process process = new Process(); //创建进程对象
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/C "+command;
//startInfo.Arguments = "/x " + command;
startInfo.UseShellExecute = false; // 不使用系统外壳true,false
startInfo.RedirectStandardInput = false; //不重定向输入false
startInfo.RedirectStandardOutput = true; // false true//重定向输出
startInfo.CreateNoWindow = true;//false;true //不创建窗口
process.StartInfo = startInfo;
try
{
/*
* 同步掉用
if (process.Start()) // 开始进程
{
if (seconds == 0)
{
process.WaitForExit(); //这里无限等待进程结束
}
else
{
process.WaitForExit(seconds); //等待进程结束,等待时间为指定的毫秒
}
output = process.StandardOutput.ReadToEnd(); //读取进程的输出
InsertMessage(output);
}
*/
/*
* 异步调用
*/
process.OutputDataReceived += new DataReceivedEventHandler(cmdProcess_OutputDataReceived);
process.Start();
process.BeginOutputReadLine();
//Application.DoEvents();
}
catch (System.Exception ex)
{
}
finally
{
}
}
}