本文介绍了如何限制每个时间量的方法,使用情况如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
它是微不足道的,但我就是无法通过它。 我有限制的任务量(假设连接,发送的电子邮件或点击的按钮),每个时间。因此,如我可以每小时发送1000封电子邮件。
我该怎么做,在C#?我不知道和不关心每一个操作都会多少时间。我只是想确保了最后一小时,仅1000将被执行。
解决方案 类EventLimiter {问答LT; DateTime的> requestTimes; INT maxRequests; 时间跨度时间跨度; 公共EventLimiter(INT maxRequests,时间跨度时间跨度) { this.maxRequests = maxRequests; this.timeSpan =时间跨度; requestTimes =新的问答LT; DateTime的>(maxRequests); } 私人无效SynchronizeQueue() {,而((requestTimes.Count大于0)及和放大器;(requestTimes.Peek()添加(时间跨度)LT; DateTime.UtcNow)) requestTimes.Dequeue(); } 公共BOOL CanRequestNow() { SynchronizeQueue(); 返回requestTimes.Count< maxRequests; } 公共无效EnqueueRequest() {,而(!CanRequestNow())的Thread.Sleep(requestTimes.Peek()。添加(时间跨度).Subtract(DateTime.UtcNow)); //为:System.Threading.Thread.Sleep(1000); requestTimes.Enqueue(DateTime.UtcNow); } }
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 e.g. I can send 1000 emails per hour.
How can I do that in c#? I don't know and don't care how much time each operation will take. I just want to make sure that for last hour, only 1000 will be executed.
解决方案 class EventLimiter { Queue<DateTime> requestTimes; int maxRequests; TimeSpan timeSpan; public EventLimiter(int maxRequests, TimeSpan timeSpan) { this.maxRequests = maxRequests; this.timeSpan = timeSpan; requestTimes = new Queue<DateTime>(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); } }
更多推荐
如何限制每个时间量的方法,使用情况如何?
发布评论