public void ReserveTellsYouHowLongToWait()
    {
        var clock   = new FakeSystemClock();
        var limiter = new Limiter(new Limit(10), 50, clock);

        var initiallyAllowed = limiter.AllowN(clock.UtcNow, 50);
        var thenNotAllowed1  = limiter.Allow();

        var reserveOne = limiter.Reserve();
        var delayOne   = reserveOne.Delay();

        var reserveTwoMore = limiter.Reserve(clock.UtcNow, 2);
        var delayTwoMore   = reserveTwoMore.Delay();

        clock.Advance(TimeSpan.FromMilliseconds(450));

        var reserveAlreadyAvailable = limiter.Reserve();
        var delayAlreadyAvailable   = reserveAlreadyAvailable.Delay();

        var reserveHalfAvailable = limiter.Reserve();
        var delayHalfAvailable   = reserveHalfAvailable.Delay();

        Assert.True(initiallyAllowed);
        Assert.False(thenNotAllowed1);
        Assert.True(reserveOne.Ok);
        Assert.Equal(TimeSpan.FromMilliseconds(100), delayOne);
        Assert.True(reserveTwoMore.Ok);
        Assert.Equal(TimeSpan.FromMilliseconds(300), delayTwoMore);
        Assert.True(reserveAlreadyAvailable.Ok);
        Assert.Equal(TimeSpan.Zero, delayAlreadyAvailable);
        Assert.True(reserveHalfAvailable.Ok);
        Assert.Equal(TimeSpan.FromMilliseconds(50), delayHalfAvailable);
    }
 /// <summary>
 /// When gets an item and gets to decide how long that item should wait.
 /// </summary>
 /// <param name="item">The item.</param>
 /// <returns>TimeSpan.</returns>
 public TimeSpan ItemDelay(TItem item)
 {
     return(_limiter.Reserve().Delay());
 }
Exemple #3
0
 protected override async Task OnGetAsync(CancellationToken cancellationToken)
 {
     var delay = _limiter.Reserve().Delay();
     await Task.Delay(delay, cancellationToken);
 }