如何限制每个时间量的方法,使用情况如何?

编程入门 行业动态 更新时间:2024-10-09 00:40:01
本文介绍了如何限制每个时间量的方法,使用情况如何?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

它是微不足道的,但我就是无法通过它。 我有限制的任务量(假设连接,发送的电子邮件或点击的按钮),每个时间。因此,如我可以每小时发送1000封电子邮件。

我该怎么做,在C#?我不知道和不关心每一个操作都会多少时间。我只是想确保了最后一小时,仅1000将被执行。

解决方案

类EventLimiter {问答LT; D​​ateTime的> requestTimes; INT maxRequests; 时间跨度时间跨度; 公共EventLimiter(INT maxRequests,时间跨度时间跨度) { this.maxRequests = maxRequests; this.timeSpan =时间跨度; requestTimes =新的问答LT; D​​ateTime的>(maxRequests); } 私人无效SynchronizeQueue() {,而((requestTimes.Count大于0)及和放大器;(requestTimes.Peek()添加(时间跨度)LT; D​​ateTime.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); } }

更多推荐

如何限制每个时间量的方法,使用情况如何?

本文发布于:2023-11-23 07:05:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1620549.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:情况   时间   方法

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!