引用:http://www.jiamaocode.com/Cts/1031.html
异步输出
C# 代码
Process p = CreateProcess("cmd",dir);
p.Start();
p.StandardInput.WriteLine("\"" + filename + "\" " + args);
p.StandardInput.WriteLine("exit");
string result = p.StandardOutput.ReadToEnd();
p.WaitForExit();
上面的做法本身没有什么问题,但有二个缺点。
1,如果执行的程序有大量的输出信息,会导致进程阻塞,程序至此不会再跑。
2,如果我要同步获取输出信息也不可能,只能等所有的执行完成才行。
下面我们来解决这个问题:
首先定义一个工厂用来生成进程:
C# 代码
public static Process CreateProcess(string filename, string dir)
{
Process p = new Process();
p.StartInfo.FileName = filename;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardError = true;
if (!string.IsNullOrEmpty(dir))
p.StartInfo.WorkingDirectory = dir;
return p;
}
然后我们调用它生成一个进程:
C# 代码
Process p = CreateProcess(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System),"cmd.exe"), dir);
StringBuilder result = new StringBuilder();
p.ErrorDataReceived += new DataReceivedEventHandler(delegate(object sender, DataReceivedEventArgs e)
{
result.AppendLine(e.Data);
});
p.OutputDataReceived += new DataReceivedEventHandler(delegate(object sender, DataReceivedEventArgs e)
{
ShowNormalInfo(e.Data);
result.AppendLine(e.Data);
});
p.Start();
p.BeginErrorReadLine();
p.BeginOutputReadLine();
p.StandardInput.WriteLine("exit");
p.WaitForExit();
p.Close();
p.Dispose();