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; } }