// *********************************************************************** // Assembly : Construction // Author : flythink // Created : 06-05-2020 // // Last Modified By : flythink // Last Modified On : 09-01-2020 // *********************************************************************** // // Copyright (c) jindongfang. All rights reserved. // // // *********************************************************************** namespace Fk.Utils { using System; using System.Threading; using Timer = System.Timers.Timer; /// /// Delegate SlowDownAction /// public delegate void SlowDownAction(); /// /// Class SlowDownTimer. /// public class SlowDownTimer : IDisposable { private SlowDownAction action; private Timer onceTimer; private SynchronizationContext synchronizationContext; private bool disposed = false; /// /// Initializes a new instance of the class. /// /// The interval. /// 是否重复执行 public SlowDownTimer(double interval, bool autoReset = false) { this.synchronizationContext = SynchronizationContext.Current; this.onceTimer = new Timer(interval); this.onceTimer.AutoReset = autoReset; this.onceTimer.Elapsed += this.OnceTimer_Elapsed; } /// /// Finalizes an instance of the class. /// ~SlowDownTimer() { this.Dispose(false); } /// public void Dispose() { if (!this.disposed) { this.Dispose(true); } GC.SuppressFinalize(this); } /// /// 释放非托管数据 /// /// 是否非托管 protected virtual void Dispose(bool disposing) { if (!this.disposed) { if (this.onceTimer != null) { this.onceTimer.Elapsed -= this.OnceTimer_Elapsed; this.onceTimer.Close(); this.onceTimer.Dispose(); } // Violates rule: DisposableFieldsShouldBeDisposed. // Should call aFieldOfADisposableType.Dispose(); this.disposed = true; // Suppress finalization of this disposed instance. if (disposing) { GC.SuppressFinalize(this); } } } /// /// Invokes the specified action. /// /// The action. public void Invoke(SlowDownAction action) { this.onceTimer.Stop(); this.action = action; this.onceTimer.Start(); } private void OnceTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { this.synchronizationContext.Post(_ => { this.action?.Invoke(); }, null); } } }