namespace CalendarNotepad.Extends
{
///
/// 防止抖动执行任务
///
public class Shaking
{
///
/// 下一个要执行的任务
///
protected Task? Next { get; set; }
///
/// 执行计时器
///
protected System.Timers.Timer Timer { get; set; }
///
/// 等待执行时间
///
public int TimespanSeconds { get; set; }
///
/// 使用默认方式实例化
///
public Shaking() : this(5) { }
///
/// 实例化,默认抖动执行间隔5秒
///
/// 抖动执行时间间隔。秒
public Shaking(int timeSpanSeconds) {
this.TimespanSeconds = timeSpanSeconds * 1000;
this.Timer = new System.Timers.Timer {
Interval = this.TimespanSeconds
};
this.Timer.Elapsed += Timer_Tick;
this.Timer.Stop();
}
protected void Timer_Tick(object? sender,EventArgs e) {
this.Timer.Stop();
this.Timer.Dispose();
if(this.Next == null) {
return;
}
var n = this.Next;
this.Next = null;
n.Start();
}
///
/// 防抖执行任务
///
/// 要执行的任务
public void Run(Task task) {
this.Next = task;
if(this.Timer != null) {
this.Timer.Stop();
this.Timer.Dispose();
}
this.Timer = new System.Timers.Timer {
Interval = this.TimespanSeconds,
};
this.Timer.Elapsed += Timer_Tick;
this.Timer.Start();
}
///
/// 防抖执行委托
///
/// 要执行的委托
public void Run(Action action) => Run(new Task(action));
}
}