Exemplo n.º 1
0
        /// <summary>处理每一个定时器</summary>
        /// <param name="timer"></param>
        private void ProcessItem(TimerX timer)
        {
            TimerX.Current = timer;

            var sw = new Stopwatch();

            sw.Start();

            try
            {
                timer.Calling = true;

                timer.Callback(timer.State ?? timer);
            }
            catch (ThreadAbortException) { throw; }
            catch (ThreadInterruptedException) { throw; }
            // 如果用户代码没有拦截错误,则这里拦截,避免出错了都不知道怎么回事
            catch (Exception ex) { XTrace.WriteException(ex); }
            finally
            {
                sw.Stop();

                var d = (Int32)sw.ElapsedMilliseconds;
                if (timer.Cost == 0)
                {
                    timer.Cost = d;
                }
                else
                {
                    timer.Cost = (timer.Cost + d) / 2;
                }

                if (d > 500 && !timer.Async)
                {
                    XTrace.WriteLine("任务 {0} 耗时过长 {1:n0}ms", timer, d);
                }

                // 再次读取周期,因为任何函数可能会修改
                var p = timer.Period;

                timer.Timers++;
                timer.NextTime = DateTime.Now.AddMilliseconds(p);
                timer.Calling  = false;

                // 清理一次性定时器
                if (p <= 0)
                {
                    timer.Dispose();
                }
                else if (p < period)
                {
                    period = p;
                }

                TimerX.Current = null;
            }
        }