45 lines
1.2 KiB
C#
45 lines
1.2 KiB
C#
using System;
|
|
using System.Diagnostics;
|
|
|
|
namespace YwxAppWpfDanMu.Utils
|
|
{
|
|
public class RateLimiter
|
|
{
|
|
private readonly int _maxActionsPerSecond;
|
|
private readonly Stopwatch _stopwatch;
|
|
private int _actionCount;
|
|
private long _lastResetTicks;
|
|
|
|
public RateLimiter(int maxActionsPerSecond)
|
|
{
|
|
if (maxActionsPerSecond <= 0)
|
|
throw new ArgumentOutOfRangeException(nameof(maxActionsPerSecond));
|
|
|
|
_maxActionsPerSecond = maxActionsPerSecond;
|
|
_stopwatch = Stopwatch.StartNew();
|
|
_lastResetTicks = _stopwatch.ElapsedTicks;
|
|
}
|
|
|
|
public bool TryAcquire()
|
|
{
|
|
long elapsedTicks = _stopwatch.ElapsedTicks;
|
|
long ticksPerSecond = Stopwatch.Frequency;
|
|
|
|
// 检查是否需要重置计数器
|
|
if (elapsedTicks - _lastResetTicks >= ticksPerSecond)
|
|
{
|
|
_actionCount = 0;
|
|
_lastResetTicks = elapsedTicks;
|
|
}
|
|
|
|
// 检查是否超过限制
|
|
if (_actionCount >= _maxActionsPerSecond)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
_actionCount++;
|
|
return true;
|
|
}
|
|
}
|
|
} |