/* * 带超时的线程管理 * 肖俊 * 2014-8-21 */ using System; using System.Collections.Generic; using System.Threading; namespace AllBase { /// /// 带超时的线程管理 /// public class Threadx { /// /// 超时:秒 /// public int TimeOut = 30; /// /// 主线程 /// private Thread t=null; /// /// 判断是否结束线程 /// private Thread te = null; /// /// 启动时间 /// public DateTime StartTime; /// /// 是否存活 /// public bool IsActive { get { try { return (t == null ? false : t.IsAlive); } catch { return false; } } } /// /// 线程名称 /// public string Name = ""; /// /// 初始化 /// /// 要启动的线程 public Threadx(Thread ts) { t = ts; te = new Thread(End); } /// /// 初始化 /// /// 要启动的线程 /// 启动时间 public Threadx(Thread ts, DateTime dt) { StartTime = dt; t = ts; Start(); } /// /// 初始化+立即启动 /// /// 要启动的线程 /// 超时 public Threadx(Thread ts, int timeOut) { t = ts; TimeOut = timeOut; te = new Thread(End); Start(); } /// /// 初始化+立即启动 /// /// 要启动的线程 /// 超时 /// 名称 public Threadx(Thread ts, int timeOut, string name) { Name = name; t = ts; TimeOut = timeOut; te = new Thread(End); Start(); } /// /// 启动,以最低优先级运行 /// public void Start() { StartTime = DateTime.Now; if(t==null || t.IsAlive) return; try { t.Priority = ThreadPriority.Lowest; t.Start(); if(te==null) return; te.Priority = ThreadPriority.BelowNormal; te.Start(); } catch { Abort(); } } /// /// 终止线程 /// public void Abort() { try { if (t != null && t.IsAlive) t.Abort(); if(te!=null && te.IsAlive) te.Abort(); t = null; te = null; } catch { } } /// /// 判断超时与自动结束 /// private void End() { if(t==null) return; int i = 0; while (t!=null && t.IsAlive && i < 10 * TimeOut) { Thread.Sleep(100); i++; } if (t != null && t.IsAlive) Abort(); } /// /// 线程队列批量启动与执行超时控制 /// /// 线程队列 /// 超时(单位秒) /// 启动等待(单位毫秒) public static void ThreadListTimeOut(ref List ts, int timeOut, int sleep) { if (timeOut < 1) return; try { int i; for (i = 0; i < ts.Count; i++) { if(!ts[i].IsAlive) ts[i].Start(); if (sleep > 0 && i < ts.Count - 1) Thread.Sleep(sleep); } i = 0; while (ts.Count > 0 && i < 1000) { if (ts[0] == null || !ts[0].IsAlive) ts.RemoveAt(0); Thread.Sleep(timeOut); i++; } while (ts.Count > 0) { try { if (ts[0] != null && ts[0].IsAlive) ts[0].Abort(); } catch { } ts.RemoveAt(0); } } catch { } } /// /// 等待队列 /// /// 线程队列 /// 新增线程 /// 线程总数 public static void ThreadListWait(ref List ts, Thread t, int count, object obj = null) { t.IsBackground = true; if (obj != null) t.Start(obj); else t.Start(); ts.Add(t); if (ts.Count < count) return; while (ts.Count >= count) { for (int i = 0; i < ts.Count; i++) { if (ts[i] == null || !ts[i].IsAlive) { ts.RemoveAt(i); i--; } } Thread.Sleep(10); } } /// /// 等待队列完全结束 /// /// 线程队列 public static void ThreadListWait(ref List ts) { while (ts.Count > 0) { if (ts[0] == null || !ts[0].IsAlive) ts.RemoveAt(0); Thread.Sleep(10); } } } }