From your comment on Mehdi's answer I see that the task duration can be much greater than the timer interval and your original solution is OK for that situation.
The problem is how to repeat a task, not every 500ms, but 500ms after the task has completed.
You have the timer based solution which can be tidied up by setting AutoReset = false so that the timer always stops when it fires.
System.Timers.Timer t;
void StartTimer() {
t = new System.Timers.Timer();
t.Interval = 500;
t.AutoReset = false;
t.Elapsed += TimerProc;
t.Enabled = true;
}
void TimerProc(object sender, System.Timers.ElapsedEventArgs e) {
Task();
t.Enabled = true;
}
void Task() {
}
An alternative approach would be a thread running a loop.
bool repeating;
Thread th;
void StartThread() {
repeating = true;
th = new Thread(new ThreadStart(ThreadProc));
th.IsBackground = true;
th.Start();
}
void ThreadProc() {
while (repeating) {
Task();
Thread.Sleep(500);
}
}
void Task() {
}
There is little difference between the two techniques and I would probably choose the timer but I'm sure many would prefer the explicit thread approach as it does make it very clear what is happening.
i.e. task - delay - task - delay...
Alan.