-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRateLimiter.cs
More file actions
50 lines (44 loc) · 1.35 KB
/
RateLimiter.cs
File metadata and controls
50 lines (44 loc) · 1.35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
using System;
using System.Threading;
using System.Threading.Tasks;
namespace LastFM.ReaderCore
{
public class RateLimiter
{
private readonly SemaphoreSlim _semaphore;
private readonly int _maxRequestsPerSecond;
private readonly TimeSpan _interval;
private readonly object _lock = new object();
private DateTime _lastRequestTime;
public RateLimiter(int maxRequestsPerSecond = 5)
{
_maxRequestsPerSecond = maxRequestsPerSecond;
_interval = TimeSpan.FromSeconds(1.0 / maxRequestsPerSecond);
_semaphore = new SemaphoreSlim(1, 1);
_lastRequestTime = DateTime.MinValue;
}
public async Task WaitForTokenAsync()
{
await _semaphore.WaitAsync();
try
{
var now = DateTime.UtcNow;
var timeSinceLastRequest = now - _lastRequestTime;
if (timeSinceLastRequest < _interval)
{
var delay = _interval - timeSinceLastRequest;
await Task.Delay(delay);
}
_lastRequestTime = DateTime.UtcNow;
}
finally
{
_semaphore.Release();
}
}
public void Dispose()
{
_semaphore.Dispose();
}
}
}