views:

55

answers:

4

What's the best way, in C# to keep track of the number 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!

A: 

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.

Polatrite
A: 

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).

Foxfire
A: 

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.

Neil Whitaker
+2  A: 

There was a similar question here.

The language for that question is Python, but it should be easy to see how to convert the accepted answer (written in Python-like pseudocode) to C#.

Mark Byers