1、线程

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;

namespace Common
{
    public class FFmpeg
    {
        int timeCount;
        string creTimeStr;
        string rowId;
        string compPath;
        string speedStr = ".";
        public void Execute(string para, string ffmpegPath, string timestr, string Id, string targetUrl)
        {
            try
            {
                //Task.Run(() =>
                //{
                new Thread(()=> {
                //ThreadPool.SetMinThreads(1, 1);
                //ThreadPool.SetMaxThreads(1, 1);
                //ThreadPool.QueueUserWorkItem(new WaitCallback(pool=> {
                    this.creTimeStr = timestr;
                    this.rowId = Id;
                    this.compPath = targetUrl;
                    //
                    Process p = new Process();
                    p.StartInfo.FileName = ffmpegPath;
                    p.StartInfo.Arguments = para;  //执行参数
                    p.StartInfo.UseShellExecute = false;
                    p.StartInfo.CreateNoWindow = true;
                    p.StartInfo.RedirectStandardInput = true;
                    p.StartInfo.RedirectStandardOutput = true;
                    p.StartInfo.RedirectStandardError = true;//把外部程序错误输出写到StandardError流中
                    p.ErrorDataReceived += new DataReceivedEventHandler(p_ErrorDataReceived);
                    p.OutputDataReceived += new DataReceivedEventHandler(p_OutputDataReceived);
                    using (p)
                    {
                        p.Start();
                        p.BeginErrorReadLine();//开始异步读取
                        p.WaitForExit();//阻塞等待进程结束
                        string sqlStr = "UPDATE Tbl_File SET File_Path2='" + this.compPath + "',File_State='压缩成功' where ID=" + this.rowId;
                        int count = Common.DataLink.ExecuteSql(sqlStr);
                        if (count <= 0)
                        {
                            Logger.Info("压缩进度完结失败!" + this.rowId);
                        }
                        p.Close();//关闭进程
                        p.Dispose();//释放资源

                    }
                //}));
                }).Start();
            //});
        }
            catch (Exception ex)
            {
                Logger.Fatal("进程进程失败!" + ex);
            }
        }

        private void p_ErrorDataReceived(object sender, DataReceivedEventArgs e)
        {
            try
            {
                var output = e.Data;
                if (output != null)
                {
                    if (output.Contains("Duration"))
                    {
                        Int32 indexOfDuration = output.IndexOf("Duration");
                        Int32 indexOfBegin = output.IndexOf(":", indexOfDuration);
                        Int32 indexOfEnd = output.IndexOf(",", indexOfBegin);
                        var duration = output.Substring(indexOfBegin + 1, indexOfEnd - indexOfBegin - 1);
                        this.timeCount = ConvertStringtoSecond(duration);
                        Logger.Info("id:" + this.rowId + "|视频时间:" + this.timeCount);
                    }
                    if (output.Contains("time="))
                    {
                        string nowTime = DateTime.Now.ToString("yyy/MM/dd HH:mm:ss");
                        TimeSpan ts = DateTime.Parse(nowTime) - DateTime.Parse(creTimeStr);
                        var minuteTime = ts.Days * 24 + ts.Hours * 60 + ts.Minutes * 60 + ts.Seconds;
                        //
                        Int32 indexOfTime = output.IndexOf("time=");
                        Int32 indexOfBegin = output.IndexOf("=", indexOfTime);
                        Int32 indexOfEnd = output.IndexOf("bitrate", indexOfBegin);
                        string timeStr = output.Substring(indexOfBegin + 1, indexOfEnd - indexOfBegin - 1);
                        //
                        var time = Convert.ToDouble(ConvertStringtoSecond(timeStr));
                        //
                        var process = time / this.timeCount * 100;  //当前毫秒单位
                        process = Math.Round(process);
                        //if (string.IsNullOrWhiteSpace(Convert.ToString(CacheHelper.Instance.Get(uuidN))))
                        //{
                        //    CacheHelper.Instance.Add(uuidN, string.Format("{0}%", process), 30);
                        //}
                        //else
                        //{
                        //    CacheHelper.Instance.Update(uuidN, string.Format("{0}%", process), 30);
                        //}
                        //Console.Write("{0}% ", process);
                        Logger.Info("id:" + this.rowId + "|压缩进度:" + process + "%");
                        if (minuteTime > 30 && process != 100)
                        {
                            this.creTimeStr = nowTime;
                            Logger.Info("id:" + this.rowId + "|每隔间段压缩进度:" + process + "%");
                            if (double.IsPositiveInfinity(process) || double.IsNegativeInfinity(process) || double.IsNaN(process)) //非无穷大
                            {
                                switch (speedStr)
                                {
                                    case ".":
                                        speedStr = "..";
                                        break;
                                    case "..":
                                        speedStr = "...";
                                        break;
                                    case "...":
                                        speedStr = ".";
                                        break;
                                    default:
                                        break;
                                }
                                string sqlStr = "UPDATE Tbl_File SET File_State='压缩处理中" + speedStr + "' where ID=" + this.rowId;
                                int count = Common.DataLink.ExecuteSql(sqlStr);
                            }
                            else
                            {
                                string sqlStr = "UPDATE Tbl_File SET File_State='" + "压缩进度..." + process + "%' where ID=" + this.rowId;
                                int count = Common.DataLink.ExecuteSql(sqlStr);
                            }
                        }
                        else if (process == 100)
                        {
                            Logger.Info("id:" + this.rowId + "|完成压缩进度:" + process + "%");
                            //string sqlStr = "UPDATE Tbl_File SET File_Path2='" + this.compPath + "',File_State='压缩成功' where ID=" + this.rowId;
                            //int count = Common.DataLink.ExecuteSql(sqlStr);
                        }
                    }
                    //Console.WriteLine(e.Data);
                }
            }
            catch (Exception ex)
            {
                //Logger.Fatal("压缩进度读取失败!" + ex);
            }

        }

        private static int ConvertStringtoSecond(string timeStr)
        {
            int totalSecond = 0;
            try
            {
                DateTime dateTime = Convert.ToDateTime(timeStr);
                totalSecond = dateTime.Hour * 3600000 + dateTime.Minute * 60000 + dateTime.Second * 1000 + dateTime.Millisecond;
            }
            catch (System.Exception ex)
            {
                Console.Write(ex.Message);
            }
            return totalSecond;
        }

        private static void p_OutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            Console.WriteLine(e.Data);
        }


    }
}

 

进程限制

        public void Execute(string para, string ffmpegPath, string timestr, string Id, string targetUrl)
        {
            try
            {
                Task.Run(() =>
                {
                    Task.Delay(DateTime.Now.Second * 500);
                    System.Timers.Timer timer = new System.Timers.Timer(5000);
                    timer.Elapsed += delegate (object sender, System.Timers.ElapsedEventArgs e)
                    {
                        if (System.Diagnostics.Process.GetProcessesByName("ffmpeg").Length < 2)
                        {
                            timer.Enabled = false;
                            System.Diagnostics.Debug.WriteLine(Id + "压缩中...");
                            this.creTimeStr = timestr;
                            this.rowId = Id;
                            this.compPath = targetUrl;
                            Thread thread = Thread.CurrentThread;
                            Process p = new Process();
                            p.StartInfo.FileName = ffmpegPath;
                            p.StartInfo.Arguments = para;  //执行参数
                            p.StartInfo.UseShellExecute = false;
                            p.StartInfo.CreateNoWindow = true;
                            p.StartInfo.RedirectStandardInput = true;
                            p.StartInfo.RedirectStandardOutput = true;
                            p.StartInfo.RedirectStandardError = true;//把外部程序错误输出写到StandardError流中
                            p.ErrorDataReceived += new DataReceivedEventHandler(p_ErrorDataReceived);
                            p.OutputDataReceived += new DataReceivedEventHandler(p_OutputDataReceived);
                            using (p)
                            {
                                p.Start();
                                p.BeginErrorReadLine();//开始异步读取
                                p.WaitForExit();//阻塞等待进程结束
                                string sqlStr = "UPDATE Tbl_File SET File_Path2='" + this.compPath + "',File_State='压缩成功' where ID=" + this.rowId;
                                int count = Common.DataLink.ExecuteSql(sqlStr);
                                if (count <= 0)
                                {
                                    Logger.Info("压缩进度完结失败!" + this.rowId);
                                }
                                p.Close();//关闭进程
                                p.Dispose();//释放资源
                            }
                        }
                    };
                    timer.Enabled = true;
                });
            }
            catch (Exception ex)
            {
                Logger.Fatal("进程进程失败!" + ex);
            }
        }

 

点到为止