Reputation: 51
I'm developing a windows service that will need to do multiple tasks at different periods.
I currently have two timers, a full timer and a stock timer running at different intervals defined like below.
fullTimer = new System.Timers.Timer();
fullTimer.Elapsed += new ElapsedEventHandler(OnElapsedTime);
fullTimer.Interval = Convert.ToDouble(interval * 1000);
fullTimer.AutoReset = true;
fullTimer.Start(); // or fullTimer.Enabled = true;
GC.KeepAlive(fullTimer);
stockTimer = new System.Timers.Timer();
stockTimer.Elapsed += new ElapsedEventHandler(StockOnElapsedTime);
stockTimer.Interval = Convert.ToDouble(stockInterval * 1000);
stockTimer.AutoReset = true;
stockTimer.Start();
GC.KeepAlive(stockTimer);
Can anyone see why the timers wouldn't be firing. I'm getting really strange behaviour. If i fire the stock handler manually
StockOnElapsedTime(null,null);
The timer seems to continue to fire correctly.
Upvotes: 3
Views: 3967
Reputation: 1
As far as garbage collection goes, if the timer objects are both static class fields then the current instances of them will not be garbage collected unless you later set the fields to null or to a new object, so GC.KeepAlive is unnecessary (and it wouldn't have helped where it was being used anyway). Where is this code being called, within OnStart?
Upvotes: 0
Reputation: 887453
You should store the Timer
instances in fields.
Calling GC.KeepAlive
will not keep an object alive indefinitely.
Upvotes: 0
Reputation: 24988
From the docs on GC.KeepAlive, I'd say that you might want to check that it's doing what you think it's doing. The garbage collector will only guarantee to keep the objects alive between the start of the method to the point that KeepAlive is called. Can you make these members of an object that'll stay around?
Upvotes: 2