Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- namespace ConsoleApp2
- {
- using System;
- using System.Threading;
- public class RpsExecuter
- {
- private System.Timers.Timer Timer { get; }
- private int _tokensLeft;
- private readonly int _maxTokens;
- public RpsExecuter(int maxRequests, TimeSpan perInterval)
- {
- if (maxRequests < 1)
- {
- throw new ArgumentException(nameof(maxRequests));
- }
- if (perInterval.TotalMilliseconds < 1)
- {
- throw new ArgumentException(nameof(perInterval));
- }
- _maxTokens = maxRequests;
- _tokensLeft = maxRequests;
- var msPeriod = perInterval.TotalMilliseconds / maxRequests;
- Timer = new System.Timers.Timer(msPeriod);
- Timer.Elapsed += (o, e) => TryPutToken();
- Timer.Start();
- }
- private void TryPutToken()
- {
- var tokens = Interlocked.Increment(ref _tokensLeft);
- if (tokens > _maxTokens)
- {
- Interlocked.Decrement(ref _tokensLeft);
- }
- }
- private bool TryPullToken()
- {
- var permission = Interlocked.Decrement(ref _tokensLeft);
- if (permission >= 0)
- return true;
- Interlocked.Increment(ref _tokensLeft);
- return false;
- }
- public bool CanExecute()
- {
- return TryPullToken();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement