简体   繁体   English

如何在后台启动进程并读取标准 output

[英]How to start a process in the background and read standard output

I am new to C#, I have to start a very time consuming process from my C# program of course without bearing the loss of ui freeze, also I want to read the output printed by the program in cmd and at last I want a stop button so that I can close the program whenever I want... I am new to C#, I have to start a very time consuming process from my C# program of course without bearing the loss of ui freeze, also I want to read the output printed by the program in cmd and at last I want a stop button这样我就可以随时关闭程序...

Please help..请帮忙..

try:尝试:

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);

for ending the process:结束进程:

p.close()

Use something like this:使用这样的东西:

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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM