Advertisements
Home > Misc > Duplicate record execution with System.Timer Elapsed event

Duplicate record execution with System.Timer Elapsed event

We have a windows service with System.Timer control which periodically polls the records from Data Base and processes in its Elapsed event as below.

protected void Timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)        {

// Business logic goes here

}

Everything seems working fine until we noticed few records executing twice causing inconsistency.

The issue was random and unable to reproduce consistently.

Reason

  • Culprit was System.Timer’s Elapsed event
  • Assume the timer’s duration is 3 seconds, so every seconds Elapsed event kick in and executes the business logic. What happens if previous elapsed event would not complete before next Elapsed event ticks in.
  • This is exactly what happened in our case and caused duplicate execution of records.

Fix

  • We restricted overlap of Elapsed event using a Static variable as below

        protected static bool isInExecution = false;

protected void Timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)        {

if (isInExecution) return;

isInExecution = true;

// Business logic goes here

isInExecution = false;

}

🙂

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave 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

%d bloggers like this: