.NET Standard 2.0 通用扩展库!
开箱即用。
Nuget地址
:https://www.nuget.org/packages/Sesy
Gitee地址
:https://gitee.com/sesy/sesy
一、概念
节流算法是一种用于控制函数执行频率
的技术。它通过限制函数在一定时间间隔内的执行次数
,以避免过多的函数调用,提高性能
和资源利用
率。常见的节流算法有定时器
节流和时间戳
节流两种实现方式。定时器节流在函数调用后设定一个定时器,在定时器到期前不再执行函数;时间戳节流则是记录上次函数执行的时间戳,在一定时间间隔内只有当当前时间超过上次执行时间加上设定的时间间隔时才执行函数。
二、思维图
1.1 流程图
2.2 时序图
三、代码实现
/// <summary>
/// 节流调度器 用于限制函数的执行频率
/// </summary>
public class ThrottlerDispatcher
{
private bool isRunning;
/// <summary>
/// 函数节流
/// </summary>
/// <param name="action"></param>
/// <param name="delay"></param>
public void Throttle(Action action, int delay)
{
if (!isRunning)
{
action?.Invoke();
isRunning = true;
new Timer(_ =>
{
isRunning = false;
}, null, delay, Timeout.Infinite);
}
}
}
static void Main(string[] args)
{
ThrottlerDispatcher dispatcher = new ThrottlerDispatcher();
// 连续调用10次 模拟 屏幕滚动事件 或 用户输入事件
for (int i = 0; i < 10; i++)
{
// 节流,100ms 100ms内仅允许函数执行一次 后续会被屏蔽掉,避免过多的函数调用
dispatcher.Throttle(() =>
{
Console.WriteLine(i);
}, 100);
}
// 仅第一次调用被执行,后续调用都未能超过100ms的间隔,被节流函数限制执行
// 输出结果 0
Console.Read();
}