using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Timers; using System.Windows.Forms; namespace GeoSigma.SigmaDrawerUtil { public class SlowDownTimer : System.IDisposable { private System.Timers.Timer onceTimer; private Action action = null; private double interval; public SlowDownTimer(double interval) { this.interval = interval; } public void Invoke(Control c, Action ac) { if (onceTimer == null) { onceTimer = new System.Timers.Timer(this.interval); onceTimer.AutoReset = false; // 仅执行一次 onceTimer.Elapsed += OnceTimer_Elapsed; } onceTimer.Stop(); onceTimer.Start(); this.action = () => c.Invoke(new MethodInvoker(ac)); } private void OnceTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { this.action?.Invoke(); } public void Dispose() { Dispose(true); System.GC.SuppressFinalize(this); // 上面一行代码作用是防止"垃圾回收器"调用这个类中的方法 // " ~ResourceHolder() " // 为什么要防止呢? 因为如果用户记得调用Dispose()方法,那么 // "垃圾回收器"就没有必要"多此一举"地再去释放一遍"非托管资源"了 // 如果用户不记得调用,就让"垃圾回收器"帮我们去释放。 } protected virtual void Dispose(bool disposing) { if (disposing) { if (onceTimer != null) { onceTimer.Stop(); onceTimer.Dispose(); } } // 这里是清理"非托管资源"的用户代码段 } ~SlowDownTimer() { Dispose(false); } } }