Skip to content

Commit 06f91c5

Browse files
committed
Merge pull request sjdirect#90 from xavivars/fixing-ratelimiter-issues
Fixing Timer.Change issues with negative dueTimes
2 parents 6f449be + caa3af6 commit 06f91c5

File tree

1 file changed

+11
-13
lines changed

1 file changed

+11
-13
lines changed

Abot/Util/RateLimiter.cs

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -168,24 +168,22 @@ private void ExitTimerCallback(object state)
168168
// While there are exit times that are passed due still in the queue,
169169
// exit the semaphore and dequeue the exit time.
170170
int exitTime;
171-
while (_exitTimes.TryPeek(out exitTime)
172-
&& unchecked(exitTime - Environment.TickCount) <= 0)
171+
bool exitTimeValid = _exitTimes.TryPeek(out exitTime);
172+
while (exitTimeValid)
173173
{
174+
if (unchecked(exitTime - Environment.TickCount) > 0)
175+
{
176+
break;
177+
}
174178
_semaphore.Release();
175179
_exitTimes.TryDequeue(out exitTime);
180+
exitTimeValid = _exitTimes.TryPeek(out exitTime);
176181
}
177182

178-
// Try to get the next exit time from the queue and compute
179-
// the time until the next check should take place. If the
180-
// queue is empty, then no exit times will occur until at least
181-
// one time unit has passed.
182-
int timeUntilNextCheck;
183-
if (_exitTimes.TryPeek(out exitTime))
184-
timeUntilNextCheck = unchecked(exitTime - Environment.TickCount);
185-
else
186-
timeUntilNextCheck = TimeUnitMilliseconds;
187-
188-
// Set the timer.
183+
// we are already holding the next item from the queue, do not peek again
184+
// although this exit time may have already pass by this stmt.
185+
var timeUntilNextCheck = exitTimeValid ? Math.Min(TimeUnitMilliseconds, Math.Max(0, exitTime - Environment.TickCount)) : TimeUnitMilliseconds;
186+
189187
_exitTimer.Change(timeUntilNextCheck, -1);
190188
}
191189

0 commit comments

Comments
 (0)