Sometimes you want to delay executing an event handler, such as to record multiple occurrences and operate them in a batch, or to execute a single action for multiple similar event occurrences. The first usually happens if you want to avoid posting changes from the client side to a server too often (with too many requests), and an example for the second case is waiting until the user pauses a little during a drag and drop operation, to avoid performance issues.
Here is how I handle these situations:
- Whenever the target event occurs, instead of executing the normal action, I just start the timer (after stopping it in case it was running) and optionally collect the event arguments representing the changes into a queue;
- When the interval elapses I stop the timer and execute the normal action for the event, optionally using the prerecorded queue of changes, which I eventually clear afterwards.
This approach may be further encapsulated into a specialized component as required by the principles you develop with, and it works every time like a charm! J
Update: This behavior may also be accomplished by using the more elegant Task.Delay method of .NET’s TPL. But you’ll need to use the version with cancellation token to be able to reset the timer.