public bool Fill(int amount) { var current = Thread.VolatileRead(ref currentSize); var fillTo = current + amount; while (fillTo <= Capacity) { if (Interlocked.CompareExchange(ref currentSize, fillTo, current) == current) { return true; } current = currentSize; } return false; }
static Func<IHttpRequest, Task<HttpResponse>> Wrap(Func<IHttpRequest, Task<HttpResponse>> handler, LeakyBucket rateLimitBucket) { return request => rateLimitBucket.Fill(1) ? handler(request) : Task.FromResult(TooManyRequests); }