ProcessStartInfo hanging on “WaitForExit”? Why?

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

    The problem with unhandled ObjectDisposedException happens when the process is timed out. In such case the other parts of the condition:

    if (process.WaitForExit(timeout) 
        && outputWaitHandle.WaitOne(timeout) 
        && errorWaitHandle.WaitOne(timeout))
    

    are not executed. I resolved this problem in a following way:

    using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false))
    using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))
    {
        using (Process process = new Process())
        {
            // preparing ProcessStartInfo
    
            try
            {
                process.OutputDataReceived += (sender, e) =>
                    {
                        if (e.Data == null)
                        {
                            outputWaitHandle.Set();
                        }
                        else
                        {
                            outputBuilder.AppendLine(e.Data);
                        }
                    };
                process.ErrorDataReceived += (sender, e) =>
                    {
                        if (e.Data == null)
                        {
                            errorWaitHandle.Set();
                        }
                        else
                        {
                            errorBuilder.AppendLine(e.Data);
                        }
                    };
    
                process.Start();
    
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();
    
                if (process.WaitForExit(timeout))
                {
                    exitCode = process.ExitCode;
                }
                else
                {
                    // timed out
                }
    
                output = outputBuilder.ToString();
            }
            finally
            {
                outputWaitHandle.WaitOne(timeout);
                errorWaitHandle.WaitOne(timeout);
            }
        }
    }
    

提交回复
热议问题