ProcessStartInfo hanging on “WaitForExit”? Why?

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

    I think with async, it is possible to have a more elegant solution and not having deadlocks even when using both standardOutput and standardError:

    using (Process process = new Process())
    {
        process.StartInfo.FileName = filename;
        process.StartInfo.Arguments = arguments;
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.RedirectStandardOutput = true;
        process.StartInfo.RedirectStandardError = true;
    
        process.Start();
    
        var tStandardOutput = process.StandardOutput.ReadToEndAsync();
        var tStandardError = process.StandardError.ReadToEndAsync();
    
        if (process.WaitForExit(timeout))
        {
            string output = await tStandardOutput;
            string errors = await tStandardError;
    
            // Process completed. Check process.ExitCode here.
        }
        else
        {
            // Timed out.
        }
    }
    

    It is base on Mark Byers answer. If you are not in an async method, you can use string output = tStandardOutput.result; instead of await

提交回复
热议问题