I have following code to use timer (System.Timers.Timer) in windows service. The goal is that new time handler should not occur if previous one didn't finish its job. Here is how I achieve this:
protected override void OnStart(string[] args)
{
try
{
//
// Create and start a timer.
//
m_mainTimer = new System.Timers.Timer();
m_mainTimer.Interval = 60000; // every one min
m_mainTimer.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Tick);
m_mainTimer.AutoReset = false; // makes it fire only once
m_mainTimer.Enabled = true;
}
catch (Exception ex)
{
// omitted
}
}
And:
protected override void OnStop()
{
try
{
// Service stopped. Also stop the timer.
m_mainTimer.Enabled = false;
m_mainTimer = null;
}
catch (Exception ex)
{
}
}
Also in handler:
private void timer1_Tick(object sender, ElapsedEventArgs e)
{
try
{
}catch(Exceptione x)
{
}
finally
{
if (null != m_mainTimer)
{
m_mainTimer.Start(); // re - enable the timer
}
}
}
It works but my question is is this approach safe? Maybe I should make m_mainTimer
volatile
? Because of the null
check inside finally
?