I have some code that needs to run a Timer. The Timer checks for a condition and, based on the result, signals to the caller that it can continue. Here's my pseudocode:
class MyClass
{
private AutoResetEvent _reset;
private System.Threading.Timer _timer;
public void Run()
{
this._reset = new AutoResetEvent(false);
this._timer = new System.Threading.Timer(this.TimerStep, null, 0, 1000);
this._reset.WaitOne(); //wait for condition() to be true
this._reset.Dispose();
this._timer.Dispose();
}
private void TimerStep(object arg)
{
if(condition())
{
this._reset.Set(); //should happen after the _reset.WaitOne() call
}
}
}
My concern has to do with how I'm instantiating the Timer. If I start it with a 0 dueTime, the comments say that the timer will start immediately. What happens if the calling thread gets preempted by the timer and the this._reset.Set()
call happens before the calling thread has a chance to call this._reset.WaitOne()
? Is this something I have to worry about? So far in my testing the code works like I'd expect.
Note that I set up the code in this way because I want to block the Run()
function until condition()
is true, but I only want to check condition()
every second or so.