public bool Request()
        {
            if (limitedQueue.Count >= limitSize)
            {
                return(false);
            }
            lock (lckObj)
            {
                if (limitedQueue.Count >= limitSize)
                {
                    return(false);
                }

                return(limitedQueue.Enqueue(new object()));
            }
        }
Exemplo n.º 2
0
        public TokenBucketLimitingService(int maxTPS, int limitSize)
        {
            this.limitSize = limitSize;
            this.maxTPS    = maxTPS;

            if (this.limitSize <= 0)
            {
                this.limitSize = 100;
            }
            if (this.maxTPS <= 0)
            {
                this.maxTPS = 1;
            }

            limitedQueue = new LimitedQueue <object>(limitSize);
            for (int i = 0; i < limitSize; i++)
            {
                limitedQueue.Enqueue(new object());
            }
            cancelToken = new CancellationTokenSource();
            task        = Task.Factory.StartNew(new Action(TokenProcess), cancelToken.Token);
        }
Exemplo n.º 3
0
        /// <summary>
        /// 定时消息令牌
        /// </summary>
        private void TokenProcess()
        {
            int sleep = 1000 / maxTPS;

            if (sleep == 0)
            {
                sleep = 1;
            }

            DateTime start = DateTime.Now;

            while (cancelToken.Token.IsCancellationRequested == false)
            {
                try
                {
                    lock (lckObj)
                    {
                        limitedQueue.Enqueue(new object());
                    }
                }
                catch
                {
                }
                finally
                {
                    if (DateTime.Now - start < TimeSpan.FromMilliseconds(sleep))
                    {
                        int newSleep = sleep - (int)(DateTime.Now - start).TotalMilliseconds;
                        if (newSleep > 1)
                        {
                            Thread.Sleep(newSleep - 1); //做一下时间上的补偿
                        }
                    }
                    start = DateTime.Now;
                }
            }
        }