Reputation: 9
What I want, a windows service that performs a function with a interval, without opening multiple threads.
What I did, using a Threading.Timer I created the following code:
protected override void OnStart(string[] args) {
System.Threading.Timer timer1 = new System.Threading.Timer(new TimerCallback(Risk), null, 60000, Timeout.Infinite);
}
public void Risk(object state) {
try{
//long operation
}
catch(ex){
}
finally{
timer1.Change(1000, Timeout.Infinite);
}
}
My problem, it looks like this code is opening multiple threads. Is this possible? Where did I go wrong? This a good way to get what I want?
UPDATE (using System.Timers.Timer):
protected override void OnStart(string[] args) {
System.Timers.Timer aTimer;
aTimer = new System.Timers.Timer(60000);
aTimer.Elapsed += Risk;
aTimer.AutoReset = true;
aTimer.Enabled = true;
}
private void Risk(Object source, ElapsedEventArgs e) {
aTimer.Enabled = false;
try{}
catch(ex){}
finally{
aTimer.Interval = 1000;
aTimer.Enabled = true;
}
}
Upvotes: 0
Views: 1777
Reputation: 171206
Multiple timer ticks can run concurrently. The timer class does not wait for ticks to complete. (I think it should have such a feature because it's almost always what you want.)
An easy fix is to run an loop with Task.Delay
:
while (!cancel) {
DoStuff();
await Task.Delay(...);
}
And you kick that off with Task.Run(() => { AsyncCodeHere(); });
.
Upvotes: 1