我有一些需要运行计时器的代码。Timer 检查条件,并根据结果向调用者发出信号,表明它可以继续。这是我的伪代码:
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
}
}
}
我关心的是我如何实例化定时器。如果我以 0 dueTime 启动它,评论说计时器将立即启动。如果调用线程被定时器抢占并且this._reset.Set()
调用发生在调用线程有机会调用之前会发生this._reset.WaitOne()
什么?这是我必须担心的事情吗?到目前为止,在我的测试中,代码的工作方式与我预期的一样。
请注意,我以这种方式设置代码是因为我想阻止Run()
函数直到condition()
为真,但我只想condition()
每隔一秒左右检查一次。