I wrote a Timer class in order to use it within a windows service that is polling another system. I did this because I had two issues that the System.Timers.Timer
is not addressing.
- The Elapsed EventHanler is running in background and so its execution will abort if the main thread ends. I wanted the
System.Timers.Timer.Stop
function to block the main thread until the execution of the Elapsed EventHanler had end. System.Timers.Timer
is not dealing with event reentrance. I want the Interval to be between two Elapsed EventHanler so that the Timer wont ever call the Elapsed EventHanler if the previous call (+interval) had not finished yet.
While writing the class I found out that I would need to dael with some thrading related problems and since I m not too experienced at those I want to know if the following Timer class is Thread-Safe?
public class Timer
{
System.Timers.Timer timer = new System.Timers.Timer() { AutoReset = false };
ManualResetEvent busy = new ManualResetEvent(true);
public double Interval
{
get { return timer.Interval; }
set { timer.Interval = value; }
}
public Timer()
{
timer.Elapsed += new ElapsedEventHandler(TimerElapsed);
}
void TimerElapsed(object sender, ElapsedEventArgs e)
{
try
{
busy.Reset();
OnElapsed(e);
timer.Start();
}
finally
{
busy.Set();
}
}
public event EventHandler Elapsed;
protected void OnElapsed(EventArgs e)
{
if (Elapsed != null)
{
Elapsed(this, e);
}
}
public virtual void Start()
{
busy.WaitOne();
timer.Start();
}
public virtual void Stop()
{
busy.WaitOne();
timer.Stop();
}
}