C# Windows Service timer ticks more than one -


i'm trying make service should execute codes every second after codes execution ends. when start service , debug it, timer ticks more one, mean, codes executed twice before first execution ends.

here codes ;

timer timer1 = new timer(1000); bool _service_working = false;      protected override void onstart(string[] args)     {         timer1.elapsed += new elapsedeventhandler(runprocess);         timer1.enabled = true;         timer1.start();          _service_working = false;     }     protected override void onstop()     {         timer1.enabled = false;     }      private void runprocess(object sender, elapsedeventargs e)     {          try         {              if (_service_working == false)             {                 timer1.enabled=false;                 _service_working = true;              }              #region mycodes           }         catch (exception ex)         {             _logservice.insert_log(1022, 2, ex.message, "path : runprocess");         }                 {             _service_working = false;             timer1.enabled = true;         }       } 

when debug it, timer ticks again @ runprocess if block...

assuming you're using system.timers.timer timer events raised in background thread means without locking timer event methods can overlap.

an easy solution set autoreset false , instead in timer event restart once complete, example:

private bool terminating;  public service() {     terminating = false;      timer = new timer(1000);     timer.elapsed += new elapsedeventhandler(runprocess);     timer.enabled = true;     timer.autoreset = false; }  protected override void onstart(string[] args) {     timer.start(); }  protected override void onstop() {     terminating = true;     timer1.stop(); }  private void runprocess(object sender, elapsedeventargs e) {     // stuff      if (!terminating)         timer.start(); // restart timer } 

Comments

Popular posts from this blog

yii2 - Yii 2 Running a Cron in the basic template -

asp.net - 'System.Web.HttpContext' does not contain a definition for 'GetOwinContext' Mystery -

mercurial graft feature, can it copy? -