Created
September 3, 2018 18:24
-
-
Save Szer/f4e8fe35fc6e8f2a0d90ef86a531f923 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Threading; | |
using System.Threading.Tasks; | |
namespace ConsoleApp1 | |
{ | |
class Program | |
{ | |
static void Print() | |
{ | |
Console.WriteLine($"Invoked at: {DateTimeOffset.UtcNow}"); | |
Thread.Sleep(500); | |
} | |
static void Main(string[] args) | |
{ | |
var throttler = new Throttler(TimeSpan.FromSeconds(1), 5); | |
for (int i = 0; i < 10; i++) | |
{ | |
Thread.Sleep(100); | |
Task.Run(() => | |
{ | |
while(true) | |
{ | |
if(throttler.IsOk()) Print(); | |
} | |
}); | |
} | |
Console.ReadKey(); | |
} | |
} | |
class Throttler | |
{ | |
public Throttler(TimeSpan interval, int maxRequests) | |
{ | |
Interval = interval; | |
MaxRequests = maxRequests; | |
_timeStamps = new DateTimeOffset[maxRequests]; | |
} | |
public TimeSpan Interval { get; } | |
public int MaxRequests { get; } | |
private readonly object _locker = new object(); | |
private readonly DateTimeOffset[] _timeStamps; | |
private int _lastIndex; | |
public bool IsOk() | |
{ | |
lock (_locker) | |
{ | |
var now = DateTimeOffset.UtcNow; | |
if (now - _timeStamps[_lastIndex] >= Interval) | |
{ | |
_timeStamps[_lastIndex] = now; | |
if (_lastIndex == MaxRequests - 1) | |
{ | |
_lastIndex = 0; | |
} | |
else | |
{ | |
_lastIndex++; | |
} | |
return true; | |
} | |
return false; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment