微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 使用进程实时控制台输出重定向

我正在使用VBoxMANAGE“导出”客机. VBoxManage是一个控制台应用程序,可以控制来宾主机的行为.由于导出命令是一个漫长的过程,它返回过程更新如下:

0%… 10%… 20%… 30%… 100%

我正在编写一个使用Process调用VBoxManage的C#应用​​程序.这是我的代码

Process VBoxProc = new Process();

VBoxProc.StartInfo.FileName = VBoxMANAGE;
VBoxProc.StartInfo.Arguments = Arguments;
VBoxProc.StartInfo.UseShellExecute = false;
VBoxProc.StartInfo.CreateNowindow = true;
VBoxProc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
VBoxProc.StartInfo.RedirectStandardError = true;
VBoxProc.StartInfo.RedirectStandardOutput = true;

VBoxProc.OutputDataReceived += new DataReceivedEventHandler(VBoxProc_OutputDataReceived);
VBoxProc.ErrorDataReceived += new DataReceivedEventHandler(VBoxProc_ErrorDataReceived);

VBoxProc.EnableRaisingEvents = true;

VBoxProc.Start();
VBoxProc.BeginoutputReadLine();
VBoxProc.BeginErrorReadLine();

VBoxProc.WaitForExit();

这是很好的,除了每行读取输出.这意味着该过程更新“
0%… 10%… 20%… 30%… 100%“仅在实际过程完成后才会显示.

有没有办法实时捕获控制台输出

谢谢!

解决方法

您可以使用所有标准Stream方法直接从StanadardOutput / Error进行读取,只需确保将StartInfo.Redirectxxx设置为true.
var p = new Process()
p.StartInfo.UseShellExecute = false;  //not sure if this is absolutely required
p.StartInfo.RedirectStandardOuput = true;
....

do
{
  Thread.Sleep(nnn);
  Console.Out.Write(p.StandardOutput.ReadToEnd());
}
while (!p.HasExited);
//catch any leftovers in redirected stdout
Console.Out.Write(p.StandardOutput.ReadToEnd());

以上将回显子进程的输出到您的应用程序Standard Out.

您可以使用p.StandardOutput.Read(char [],int,int))或使用p.StadardOutput.BaseStream.BeginRead(…)的异步读取来读取特定大小的块.

所有相同的方法都可用于StandardError.

在循环中睡眠释放处理器以用于其他任务,并允许一些数据在缓冲器中累积.如果睡眠时间太长,并且缓冲区溢出,执行过程的一些输出将会丢失.如果睡眠时间太短,读取和清空缓冲区将耗费大量cpu周期.

原文地址:https://www.jb51.cc/csharp/94672.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐