ProcessStartInfo hanging on “WaitForExit”? Why?

前端 未结 22 2159
佛祖请我去吃肉
佛祖请我去吃肉 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:07

    None of the answers above is doing the job.

    Rob solution hangs and 'Mark Byers' solution get the disposed exception.(I tried the "solutions" of the other answers).

    So I decided to suggest another solution:

    public void GetProcessOutputWithTimeout(Process process, int timeoutSec, CancellationToken token, out string output, out int exitCode)
    {
        string outputLocal = "";  int localExitCode = -1;
        var task = System.Threading.Tasks.Task.Factory.StartNew(() =>
        {
            outputLocal = process.StandardOutput.ReadToEnd();
            process.WaitForExit();
            localExitCode = process.ExitCode;
        }, token);
    
        if (task.Wait(timeoutSec, token))
        {
            output = outputLocal;
            exitCode = localExitCode;
        }
        else
        {
            exitCode = -1;
            output = "";
        }
    }
    
    using (var process = new Process())
    {
        process.StartInfo = ...;
        process.Start();
        string outputUnicode; int exitCode;
        GetProcessOutputWithTimeout(process, PROCESS_TIMEOUT, out outputUnicode, out exitCode);
    }
    

    This code debugged and works perfectly.

提交回复
热议问题