What's the best way, in C# to keep track of the number 开发者_StackOverflow社区of events per timespan?
For example, I want to limit my TCP application to, say, a maximum of 10 requests per minute before setting a flag. The TCP application is intended to be as efficient as possible and runs as a windows service.
Maybe I should work on it tomorrow when my brain is less tired...
Thanks!
Check out the TimeSpan object - keep track of the DateTime when you process each event, and compare the difference using TimeSpan. If the quantity of events exceeds 10 and the TimeSpan is still under 60 seconds, you'll know to set the flag.
You cannot really limit the number of TCP "events" but you can throttle the amount of data that you send (simply by sleeping your thread that returns the data).
This way you can limit the amount of data used per TCP connection (e.g. to a maximum of 1k/sec).
Put time stamps in a queue. As long as the queue is full, don't let an event happen. When DateTime.Now - timeSpan > next_item_in_queue.TimeStamp, remove the item from the queue.
精彩评论