namespace DispenserCommon.Utils; /// /// 基于滑动时间窗口算法来判断指定时间窗口内是否存在目标值 /// public class SlidingWindow(int milliseconds, int thresold = 1) { private readonly Queue<(DateTime time, object value)> _window = new(); private readonly TimeSpan _windowSize = TimeSpan.FromMilliseconds(milliseconds); /// /// 添加值 /// /// 待添加值 public bool AllowValue(object value) { var currentTime = DateTime.Now; while (_window.Count > 0 && currentTime - _window.Peek().time > _windowSize) _window.Dequeue(); if (_window.Count < thresold) { _window.Enqueue((currentTime, value)); return true; } return false; } /// /// 判断是否已经包含了该值 /// /// 待匹配值 /// public bool Contains(object targetValue) { return _window.Any(item => item.value.Equals(targetValue)); } }