using Newtonsoft.Json; using System; using System.Collections.Concurrent; using System.Diagnostics; using System.IO; using System.Threading; using Sys... ...
using Newtonsoft.Json; using System; using System.Collections.Concurrent; using System.Diagnostics; using System.IO; using System.Threading; using System.Web; namespace TestQuenu { /// <summary> /// 文件轉碼簡單隊列 /// </summary> public class TransCodQuenuHelp { /// <summary> /// 待轉碼的文件隊列 /// </summary> private static ConcurrentQueue<string> waitTransFileQuene = new ConcurrentQueue<string>(); /// <summary> /// 系列化文件存放位置 /// </summary> private static string waitTransFileSavePath = HttpContext.Current.Server.MapPath("~/1.txt"); /// <summary> /// 等待毫秒數 /// </summary> private const int waitTime = 300000; /// <summary> /// 日誌來源 /// </summary> private const string source = ""; /// <summary> /// 日誌名稱 /// </summary> private const string logName = ""; /// <summary> /// 初始化隊列 /// </summary> public static void init() { initLog(); ReadWaitTransFile(); /*開啟線程用於定時任務*/ Thread thread = new Thread(new ThreadStart(ListenceTransCode)); thread.Start(); thread.IsBackground = true; } /// <summary> /// 初始化日誌 /// </summary> private static void initLog() { if (!EventLog.SourceExists(source)) { EventLog.CreateEventSource(source, logName); } } /// <summary> /// 轉碼監聽 /// </summary> private static void ListenceTransCode() { while (true) { if (!waitTransFileQuene.IsEmpty) { string curTransFile = string.Empty; bool isSuc = waitTransFileQuene.TryDequeue(out curTransFile); if (isSuc) { //轉碼 try { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); //doSomething(); stopwatch.Stop(); TimeSpan timespan = stopwatch.Elapsed; // 獲取當前實例測量得出的總時間 string msg = string.Format("{0}成功,用時{1}分鐘", curTransFile, timespan.TotalMinutes); EventLog.WriteEntry(source, msg, EventLogEntryType.Information); } catch (Exception ex) { EventLog.WriteEntry(source, ex.Message, EventLogEntryType.Error); } } } else { Thread.Sleep(waitTime); } } } /// <summary> /// 從文件中讀取未轉碼的文件列表 /// </summary> private static void ReadWaitTransFile() { if (File.Exists(waitTransFileSavePath)) { string waitTransFile = File.ReadAllText(waitTransFileSavePath); waitTransFileQuene = JsonConvert.DeserializeObject<ConcurrentQueue<string>>(waitTransFile); } } /// <summary> /// 保存未轉碼的文件類別到文件 /// </summary> public static void SaveWaitTransFile() { if (!waitTransFileQuene.IsEmpty) { File.WriteAllText(waitTransFileSavePath, JsonConvert.SerializeObject(waitTransFileQuene)); } } /// <summary> /// 添加新的任務 /// </summary> /// <param name="fileName">文件全名</param> public static void Add(string fileName) { waitTransFileQuene.Enqueue(fileName); } } }