public static void Add(TimerX timer) { lock (timers) { timers.Add(timer); WriteLog("TimerX.Add {0}ms {1}", timer.Period, timer); timer.OnDisposed += new EventHandler(delegate(Object sender, EventArgs e) { var tx = sender as TimerX; if (tx == null) { return; } lock (timers) { WriteLog("TimerX.Remove {0}", tx); if (timers.Contains(tx)) { timers.Remove(tx); } } }); if (thread == null) { thread = new Thread(Process); //thread.Name = "TimerX"; thread.Name = "T"; thread.IsBackground = true; thread.Start(); } if (waitForTimer != null && waitForTimer.SafeWaitHandle != null && !waitForTimer.SafeWaitHandle.IsClosed) { waitForTimer.Set(); } } }
static void ProcessItem(TimerX timer) { // 删除过期的 if (!timer.Callback.IsAlive) { lock (timers) { timers.Remove(timer); timer.Dispose(); } return; } TimeSpan ts = timer.NextTime - DateTime.Now; Int32 d = (Int32)ts.TotalMilliseconds; if (d > 0) { // 缩小间隔,便于快速调用 if (d < period) { period = d; } return; } //WriteLog("TimerX.Process {0}", timer); try { timer.Calling = true; Action <Object> callback = timer.Callback; // 线程池调用 if (timer.UseThreadPool) { ThreadPoolX.QueueUserWorkItem(delegate() { callback(timer.State); }); } else { callback(timer.State); } } catch (ThreadAbortException) { throw; } catch (ThreadInterruptedException) { throw; } catch { } finally { timer.Timers++; timer.Calling = false; timer.NextTime = DateTime.Now.AddMilliseconds(timer.Period); if (timer.Period < period) { period = timer.Period; } } }