首页 > 代码库 > System.Timer.Timer的一个安全类

System.Timer.Timer的一个安全类

class SafeTimer
    {
        private static System.Timers.Timer timer;
        public static Action DoWork;
        private static bool flag = true;
        private static object mylock = new object();

        public static void Init(double interval)
        {
            timer = new System.Timers.Timer(interval);
            timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
            timer.Start();
        }

        private static void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            Thread.CurrentThread.IsBackground = false;
            lock (mylock)
            {
                if (!flag)
                    return;
                if (DoWork != null)
                    DoWork();
            }
        }
        public static void CloseTimer()
        {
            timer.Stop();
            flag = false;
        }
    }

 

System.Timer.Timer的一个安全类