-
Notifications
You must be signed in to change notification settings - Fork 0
/
Throttler.cs
46 lines (38 loc) · 1.4 KB
/
Throttler.cs
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
namespace SimpleThrottle;
public class Throttler(int requestLimit, int timespanInMilliseconds) : IDisposable
{
private DateTime _lastRequestTime = DateTime.MinValue;
private int _requestCount = 0;
private readonly int _requestLimit = requestLimit;
private readonly int _timespanInMilliseconds = timespanInMilliseconds;
private readonly SemaphoreSlim _semaphore = new(requestLimit, requestLimit);
private readonly object _lockObject = new();
public void MakeRequest()
{
_semaphore.Wait();
// Make sure to update the request count and last request time in a thread-safe manner
lock (_lockObject)
{
if (DateTime.Now.Subtract(_lastRequestTime).TotalMilliseconds > _timespanInMilliseconds)
{
_requestCount = 0;
_lastRequestTime = DateTime.Now;
}
_requestCount++;
if (_requestCount > _requestLimit)
{
int timeToWait = (int)(_lastRequestTime.AddMilliseconds(_timespanInMilliseconds) - DateTime.Now).TotalMilliseconds;
if (timeToWait > 0)
Thread.Sleep(timeToWait);
_requestCount = 1;
_lastRequestTime = DateTime.Now;
}
}
_semaphore.Release();
}
public void Dispose()
{
_semaphore.Dispose();
GC.SuppressFinalize(this);
}
}