1

I have a Timer which I run every 10 seconds to sync local data in my app back to our servers.

public Timer syncTimer;
syncTimer = new Timer((o) =>
    { 
        this.syncToServer();

    }, null, 0, 10000);

I have a problem where if my syncToServer takes longer than 10 seconds to execute, it trips over itself. I am considering doing the following to pause the timer whilst it executes and then restart it once complete:

public Timer syncTimer;
syncTimer = new Timer((o) =>
    { 
        syncTimer.Change(Timeout.Infinite , Timeout.Infinite); //Stop the timer
        this.syncToServer();
        syncTimer.Change(10000 , 10000); //Restart the timer
    }, null, 0, 10000);

Is this the best way to achieve what I am after or is there a better way to stop it executing at the same time?

Joseph
  • 2,706
  • 6
  • 42
  • 80

1 Answers1

2

Maybe you can use System.Timers.Timer, it's more easy to understand than System.Threading.Timer.

var timer = new System.Timers.Timer(1000);
timer.AutoReset = false;
timer.Elapsed += (sender, e) => {
    this.syncToServer();
    // maybe Thread.Sleep(100000);
    timer.Start();
};
timer.Start();

May it helps.

nonocast
  • 517
  • 4
  • 14
  • The good thing about this answer is that the timer will be restarted only after the task is performed, so it's simply impossible to have re-entrancy with this scheme. – GameAlchemist Sep 28 '14 at 14:44