Here is my work-around...
After way too many hours searching for an answer to this, I discovered a wide variety of articles and blogs discussing timers in Windows services. I've seen a lot of opinions on this and they all fall into three categories and in descending order of frequency:
Don't use System.Windows.Forms.Timer
because it won't work. (this only makes sense)
Don't use System.Threading.Timer
because it doesn't work, use System.Timers.Timer
instead.
Don't use System.Timers.Timer
because it doesn't work, use System.Threading.Timer
instead.
Based on this, I tried 2. This is also the approach that seems to be recommended by Microsoft since they say that System.Timers.Timer
is suited to "Server applications".
What I've found is that System.Timers.Timer
just doesn't work in my Windows Service application. Therefore I've switched over to System.Threading.Timer
. It's a nuisance since it requires some refactoring to make it work.
This is approximately what my working code looks like now...
namespace NovaNotificationService
{
public partial class NovaNotificationService : ServiceBase
{
private System.Threading.Timer IntervalTimer;
public NovaNotificationService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
TimeSpan tsInterval = new TimeSpan(0, 0, Properties.Settings.Default.PollingFreqInSec);
IntervalTimer = new System.Threading.Timer(
new System.Threading.TimerCallback(IntervalTimer_Elapsed)
, null, tsInterval, tsInterval);
}
protected override void OnStop()
{
IntervalTimer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);
IntervalTimer.Dispose();
IntervalTimer = null;
}
private void IntervalTimer_Elapsed(object state)
{ // Do the thing that needs doing every few minutes...
// (Omitted for simplicity is sentinel logic to prevent re-entering
// DoWork() if the previous "tick" has for some reason not completed.)
DoWork();
}
}
}
I hate the "Doctor, doctor, it hurts when I do this..." solution, but that's what I had to resort to. One more opinion on the pile for the next guy with this problem...
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…