Advertisement
Guest User

Untitled

a guest
Jun 27th, 2017
229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.50 KB | None | 0 0
  1. namespace ConsoleApp2
  2. {
  3.     using System;
  4.     using System.Threading;
  5.  
  6.     public class RpsExecuter
  7.     {
  8.         private System.Timers.Timer Timer { get; }
  9.  
  10.         private int _tokensLeft;
  11.  
  12.         private readonly int _maxTokens;
  13.  
  14.         public RpsExecuter(int maxRequests, TimeSpan perInterval)
  15.         {
  16.             if (maxRequests < 1)
  17.             {
  18.                 throw new ArgumentException(nameof(maxRequests));
  19.             }
  20.             if (perInterval.TotalMilliseconds < 1)
  21.             {
  22.                 throw new ArgumentException(nameof(perInterval));
  23.             }
  24.  
  25.             _maxTokens = maxRequests;
  26.             _tokensLeft = maxRequests;
  27.  
  28.             var msPeriod = perInterval.TotalMilliseconds / maxRequests;
  29.             Timer = new System.Timers.Timer(msPeriod);
  30.             Timer.Elapsed += (o, e) => TryPutToken();
  31.             Timer.Start();
  32.         }
  33.  
  34.         private void TryPutToken()
  35.         {
  36.             var tokens = Interlocked.Increment(ref _tokensLeft);
  37.             if (tokens > _maxTokens)
  38.             {
  39.                 Interlocked.Decrement(ref _tokensLeft);
  40.             }
  41.         }
  42.  
  43.         private bool TryPullToken()
  44.         {
  45.             var permission = Interlocked.Decrement(ref _tokensLeft);
  46.             if (permission >= 0)
  47.                 return true;
  48.             Interlocked.Increment(ref _tokensLeft);
  49.             return false;
  50.         }
  51.  
  52.         public bool CanExecute()
  53.         {
  54.             return TryPullToken();
  55.         }
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement