How to limit method usage per amount of time?

前端 未结 6 1483
南旧
南旧 2020-12-31 08:12

It has to be trivial, but I just cannot get through it. I have to limit amount of tasks (let\'s say connections, emails sent or clicks in the button) per amount of time. So

6条回答
  •  被撕碎了的回忆
    2020-12-31 08:48

     class EventLimiter
     {
        Queue requestTimes;
        int maxRequests;
        TimeSpan timeSpan;
    
        public EventLimiter(int maxRequests, TimeSpan timeSpan)
        {
            this.maxRequests = maxRequests;
            this.timeSpan = timeSpan;
            requestTimes = new Queue(maxRequests);
        }
    
        private void SynchronizeQueue()
        {
            while ((requestTimes.Count > 0) && (requestTimes.Peek().Add(timeSpan) < DateTime.UtcNow))
                requestTimes.Dequeue();
        }
    
        public bool CanRequestNow()
        {
            SynchronizeQueue();
            return requestTimes.Count < maxRequests;
        }
    
        public void EnqueueRequest()
        {
            while (!CanRequestNow())               
                Thread.Sleep(requestTimes.Peek().Add(timeSpan).Subtract(DateTime.UtcNow));
                // Was: System.Threading.Thread.Sleep(1000);
    
            requestTimes.Enqueue(DateTime.UtcNow);
        }
     }
    

提交回复
热议问题