Home > Misc > ‘Duplicate record execution’ issue with System.Timer Elapsed event – Windows Service

‘Duplicate record execution’ issue with System.Timer Elapsed event – Windows Service

We have a window service with System.Timer control ‘timerExecuteQuery’, which periodically polls the records from Data Base and process.

this.timerExecuteQuery= new System.Timers.Timer(3) { AutoReset = true };
this.timerExecuteQuery.Elapsed += this.TimerExecuteQuery_Elapsed;

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

The issue was random and unable to reproduce consistently.


  • In our scenario, the culprit was System.Timer’s Elapsed event
  • Our timer’s duration is 3 seconds with ‘AutoReset=true’, so, every 3 seconds Elapsed event kick in and executes the logic.
  • In few scenarios, business logic in ‘Timer_Elapsed’ was taking more than 3 seconds causing the trigger of new Elapsed event before completion of old thread. Hence records got executed more than once randomly.


  • We declared a global Boolean variable ‘executing’ and handled as below.
    • Set variable ‘executing=true’ before Business logic of ‘Timer_Elapsed’ event and set ‘executing=false’ after execution of Business logic.
    • Check the ‘executing’ variable value before the execution of business logic, if its True, return.

private bool executing = false;

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

// ‘executing’ true denotes, previous elapsed event was not over
if (executing){

executing = true;

// Business logic
executing = false;


  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 )

Facebook photo

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

Connecting to %s

%d bloggers like this: