原文鏈接:https://www.cnblogs.com/sode/archive/2012/07/10/2583941.html
調用CMD執行命令將.h264轉換成mp4,
結果到了Process的WaitForExit()方法就一直阻塞不動,
把程序退出后轉換完成;
找了各種方法,直接輸入exit就是扯淡,操作沒完成就直接退出了;
真正的原因碰到這個問題的搬磚工應該都知道了:
以下死鎖原因部分copy
由於標准輸出流被重定向 p.StartInfo.RedirectStandardInput = true,
而Process.StandardOutput的緩沖大小是有限制的( 4k?),所以當緩沖滿了的時候(執行上面的批處理文件有很多的輸出),子進程(cmd.exe)會等待主進程(C# App)讀取並釋放此緩沖,而主進程由於調用了WaitForExit()方法,則會一進等待子進程退出,最后形成死鎖
只要訂閱處理錯誤消息就可以了,上代碼
using (Process p = new Process())
{
p.StartInfo.FileName = "ffmpeg.exe";
p.StartInfo.Arguments = convertAgrs;
p.StartInfo.UseShellExecute = false; //是否使用操作系統shell啟動
p.StartInfo.RedirectStandardInput = true; //接受來自調用程序的輸入信息
p.StartInfo.RedirectStandardOutput = true; //由調用程序獲取輸出信息
p.StartInfo.RedirectStandardError = true; //重定向標准錯誤輸出
p.StartInfo.CreateNoWindow = true; //不顯示程序窗口
p.ErrorDataReceived += new DataReceivedEventHandler(delegate (object sender, DataReceivedEventArgs e)
{
// DoSth.
//Console.WriteLine("MP4轉換error:" + e.Data);
});
p.OutputDataReceived += new DataReceivedEventHandler(delegate (object sender, DataReceivedEventArgs e)
{
// DoSth.
//Console.WriteLine($"MP4轉換信息{e.Data}");
});
p.Start();
p.BeginErrorReadLine();
p.BeginOutputReadLine();
p.WaitForExit();//等待程序執行完退出進程
p.Close();
}