private void TokenProcess() { int sleep = 1000 / maxTPS; if (sleep == 0) { sleep = 1; } DateTime start = DateTime.Now; while (cancelToken.Token.IsCancellationRequested == false) { try { if (limitedQueue.Count > 0) { lock (lckObj) { if (limitedQueue.Count > 0) { limitedQueue.Dequeue(); } } } } 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; } } }
/// <summary> /// 请求令牌 /// </summary> /// <returns>true:获取成功,false:获取失败</returns> public bool Request() { if (limitedQueue.Count <= 0) { return(false); } lock (lckObj) { if (limitedQueue.Count <= 0) { return(false); } object data = limitedQueue.Dequeue(); if (data == null) { return(false); } } return(true); }