提问者:小点点

如何在后台启动流程并读取标准输出


我是C#新手,我必须从我的C#程序开始一个非常耗时的过程,当然不需要承受ui冻结的损失,而且我想读取程序在cmd中打印的输出,最后我想要一个停止按钮,这样我可以随时关闭程序。。。

请帮忙。。


共2个答案

匿名用户

尝试:

using System.Diagnostics;

void startProcess()
{
Process p = new Process();
            p.StartInfo.FileName = "FileName";
            p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
            p.Start();

            var output = p.StandardOutput.ReadToEnd();
}

MethodInvoker starter = new MethodInvoker(startProcess);

starter.BeginInvoke(null, null);

用于结束进程:

p.close()

匿名用户

使用如下所示:

void StartProcess(){
   Process p = new Process();
   p.StartInfo.FileName = "yourfile.exe";
   p.StartInfo.UseShellExecute = false;
   p.StartInfo.RedirectStandardOutput = true;
   p.Start();
   var readingThread = new System.Threading.Thread(() => {
      while (!p.StandardOutput.EndOfStream){
         Console.WriteLine(p.StandartOutput.ReadLine());
         System.Threading.Thread.Sleep(1);
      }
   }
   readingThread.Start();
}