public override async Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) { int rateBytesPerSecond = Convert.ToInt32(_tokenBucket.Rate); if (rateBytesPerSecond <= 0) { _innerStream.Write(buffer, offset, count); return; } int tempCountBytes = count; // In the unlikely event that the count is greater than the rate (i.e. buffer // is 16KB (typically this is the max size) and the rate is < 16Kbs), we'll need // to split it into multiple. TimeSpan wait; while (tempCountBytes > rateBytesPerSecond) { if (_tokenBucket.ShouldThrottle(tempCountBytes, out wait)) { if (wait > TimeSpan.Zero) { await Task.Delay(wait, cancellationToken).ConfigureAwait(false); } } await _innerStream.WriteAsync(buffer, offset, rateBytesPerSecond, cancellationToken) .ConfigureAwait(false); offset += rateBytesPerSecond; tempCountBytes -= rateBytesPerSecond; } while (_tokenBucket.ShouldThrottle(tempCountBytes, out wait)) { if (wait > TimeSpan.Zero) { await Task.Delay(wait, cancellationToken).ConfigureAwait(false); } } await _innerStream.WriteAsync(buffer, offset, tempCountBytes, cancellationToken) .ConfigureAwait(false); }
public void Limit() { while (true) { if (!bucket.ShouldThrottle(1)) { break; } Thread.Sleep(100); } }
public void ShouldThrottle_WhenCalledWithNTokensLessThanMax_ReturnsFalse() { TimeSpan waitTime; var shouldThrottle = bucket.ShouldThrottle(N_LESS_THAN_MAX, out waitTime); Assert.False(shouldThrottle); Assert.Equal(bucket.CurrentTokenCount, MAX_TOKENS - N_LESS_THAN_MAX); }
public void ShouldThrottle_WhenCalledWithNTokensLessThanMax_ReturnsFalse() { var shouldThrottle = bucket.ShouldThrottle(N_LESS_THAN_MAX, out _); Assert.That(shouldThrottle, Is.False); Assert.That(bucket.CurrentTokenCount, Is.EqualTo(MAX_TOKENS - N_LESS_THAN_MAX)); }
public void ShouldThrottle_WhenCalledWithNTokensLessThanMax_ReturnsFalse() { TimeSpan waitTime; bool shouldThrottle = _bucket.ShouldThrottle(N_LESS_THAN_MAX, out waitTime); shouldThrottle.ShouldBeFalse(); _bucket.CurrentTokenCount.ShouldBe(MAX_TOKENS - N_LESS_THAN_MAX); }