即使使用WaitForExit(),Process()也会被阻止?

时间:2015-12-22 22:16:30

标签: c# powershell c#-4.0

处理项目。在代码中,我们需要运行powershell脚本然后获取其输出。为此,我使用Process():

    private int RunProcess(string FileName, string Arguments, out string result)
    {
        int exitCode = -1;
        result = string.Empty;
        // Start the child process.
        Process p = new Process();
        // Redirect the output stream of the child process.
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.FileName = FileName;
        p.StartInfo.Arguments = Arguments;
        p.Start();
        // Do not wait for the child process to exit before
        // reading to the end of its redirected stream.
        // Read the output stream first and then wait.
        result = p.StandardOutput.ReadToEnd();
        // Wait at most 10 minutes
        p.WaitForExit(10 * 60 * 1000);
        exitCode = p.ExitCode;
        return exitCode;
    }

并将其称为:

    RunProcess("Powershell.exe", arguments, out sPSResult);

这在大多数计算机上都能正常工作。但是,在某些情况下,由于某些不明原因,RunProcess()永远不会返回,即使我们使用p.WaitForExit(10 * 60 * 1000)。

任何人都知道为什么?或者之前看到这个?是因为在某些地方甚至在Windows中被阻止了,甚至使用WaitForExit?

由于

1 个答案:

答案 0 :(得分:0)

你确定你的代码甚至到达WaitForExit并且没有挂在ReadToEnd上吗?我的猜测是因为它无法读取所有输出而卡在那里。有关如何正确处理从子进程读取标准和错误输出的详细信息,请参阅:

ProcessStartInfo hanging on "WaitForExit"? Why?