【问题标题】:StandardOutput.ReadToEnd() hung for the second commandStandardOutput.ReadToEnd() 挂起第二个命令
【发布时间】:2020-01-10 13:37:38
【问题描述】:

我必须在 asp.net 中使用 Process 运行两个命令,如下所示,第一个命令运行成功,而第二个命令在 result = p.StandardOutput.ReadToEnd() p>

如何实现这一点以成功运行这两个命令?

private static string FFMPEG_EXE_PATH = @"D:\ffmpeg\bin\ffmpeg.exe";
private static string FFPROBE_EXE_PATH = @"D:\ffmpeg\bin\ffprobe.exe";

protected void Page_Load(object sender, EventArgs e)
{
    string firstArgs = @"-hide_banner -show_format -show_streams -pretty D:\Video\dolbycanyon.m4v";

    var result1 = Execute(FFPROBE_EXE_PATH, firstArgs);

    string secondArgs = @"-hide_banner -ss 00:00:05 -i D:\Video\dolbycanyon.m4v -r 1 -t 1 -f image2 D:\Video\test.jpg";

    var result2 = Execute(FFMPEG_EXE_PATH, secondArgs);
}

private string Execute(string exePath, string parameters)
{
    string result = String.Empty;

    using (Process p = new Process())
    {
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.CreateNoWindow = true;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.FileName = exePath;
        p.StartInfo.Arguments = parameters;
        p.Start();
        result = p.StandardOutput.ReadToEnd(); // the application hung here for the second command
        p.WaitForExit();
    }
    return result;
}

【问题讨论】:

  • 您是否尝试过手动运行第二个命令以查看它为何挂起?
  • @Martin 是的,第二个命令在命令提示符下运行顺利。

标签: asp.net process


【解决方案1】:

我已将 Execute 方法更改为如下所示,它对这两个命令都有效。

 public string Execute(string path, string args, int timeoutMs)
 {
    using (var outputWaitHandle = new ManualResetEvent(false))
    {

        using (var process = new Process())
        {
            process.StartInfo = new ProcessStartInfo(path);
            process.StartInfo.Arguments = args;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardOutput = true;

            process.StartInfo.CreateNoWindow = true;

            var sb = new StringBuilder(1024);
            process.OutputDataReceived += (sender, e) =>
            {
                sb.AppendLine(e.Data);
                if (e.Data == null)
                {
                    outputWaitHandle.Set();
                }
            };

            process.Start();
            process.BeginOutputReadLine();

            process.WaitForExit(timeoutMs);
            outputWaitHandle.WaitOne(timeoutMs);

            process.CancelOutputRead();

            return sb.ToString();
        }
    }
}

【讨论】:

    猜你喜欢
    • 2011-11-01
    • 2021-04-23
    • 1970-01-01
    • 2018-12-05
    • 2017-05-27
    • 1970-01-01
    • 1970-01-01
    • 2011-04-15
    • 1970-01-01
    相关资源
    最近更新 更多