ProcessStartInfo hanging on “WaitForExit”? Why?

前端 未结 22 2139
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 02:59

I have the following code:

info = new System.Diagnostics.ProcessStartInfo(\"TheProgram.exe\", String.Join(\" \", args));
info.CreateNoWindow = true;
info.Win         


        
22条回答
  •  执念已碎
    2020-11-22 03:08

    I thing that this is simple and better approach (we don't need AutoResetEvent):

    public static string GGSCIShell(string Path, string Command)
    {
        using (Process process = new Process())
        {
            process.StartInfo.WorkingDirectory = Path;
            process.StartInfo.FileName = Path + @"\ggsci.exe";
            process.StartInfo.CreateNoWindow = true;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardInput = true;
            process.StartInfo.UseShellExecute = false;
    
            StringBuilder output = new StringBuilder();
            process.OutputDataReceived += (sender, e) =>
            {
                if (e.Data != null)
                {
                    output.AppendLine(e.Data);
                }
            };
    
            process.Start();
            process.StandardInput.WriteLine(Command);
            process.BeginOutputReadLine();
    
    
            int timeoutParts = 10;
            int timeoutPart = (int)TIMEOUT / timeoutParts;
            do
            {
                Thread.Sleep(500);//sometimes halv scond is enough to empty output buff (therefore "exit" will be accepted without "timeoutPart" waiting)
                process.StandardInput.WriteLine("exit");
                timeoutParts--;
            }
            while (!process.WaitForExit(timeoutPart) && timeoutParts > 0);
    
            if (timeoutParts <= 0)
            {
                output.AppendLine("------ GGSCIShell TIMEOUT: " + TIMEOUT + "ms ------");
            }
    
            string result = output.ToString();
            return result;
        }
    }
    

提交回复
热议问题