CalendarNotepad/SharkingTest/Shaking.cs

71 lines
2.1 KiB
C#
Raw Normal View History

2024-07-08 13:57:07 +08:00

namespace CalendarNotepad.Extends
{
/// <summary>
/// 防止抖动执行任务
/// </summary>
public class Shaking
{
/// <summary>
/// 下一个要执行的任务
/// </summary>
protected Task? Next { get; set; }
/// <summary>
/// 执行计时器
/// </summary>
protected System.Timers.Timer Timer { get; set; }
/// <summary>
/// 等待执行时间
/// </summary>
public int TimespanSeconds { get; set; }
/// <summary>
/// 使用默认方式实例化
/// </summary>
public Shaking() : this(5) { }
/// <summary>
/// 实例化默认抖动执行间隔5秒
/// </summary>
/// <param name="timeSpanSeconds">抖动执行时间间隔。秒</param>
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();
}
/// <summary>
/// 防抖执行任务
/// </summary>
/// <param name="task">要执行的任务</param>
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();
}
/// <summary>
/// 防抖执行委托
/// </summary>
/// <param name="action">要执行的委托</param>
public void Run(Action action) => Run(new Task(action));
}
}