Delay event handling

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:

  • I define a Timer object with a short configurable interval, and define an event handler for its tick or elapsed event (.NET), or use a setInterval call (JavaScript®);
  • 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.

Advertisements

About Sorin Dolha

My passion is software development, but I also like physics.
This entry was posted in .NET, JavaScript. Bookmark the permalink.

Add a reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s