C# 如何确保以正确的顺序调用AutoResetEvent方法?
我有一些需要运行计时器的代码。计时器检查条件,并根据结果向调用者发出信号,表示可以继续。这是我的伪代码:C# 如何确保以正确的顺序调用AutoResetEvent方法?,c#,timer,autoresetevent,C#,Timer,Autoresetevent,我有一些需要运行计时器的代码。计时器检查条件,并根据结果向调用者发出信号,表示可以继续。这是我的伪代码: class MyClass { private AutoResetEvent _reset; private System.Threading.Timer _timer; public void Run() { this._reset = new AutoResetEvent(false); this._timer = new
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开始计时,评论说计时器将立即启动。如果调用线程被计时器抢占,并且this.\u reset.Set调用在调用线程有机会调用this.\u reset.WaitOne之前发生,会发生什么情况?这是我必须担心的事情吗?到目前为止,在我的测试中,代码的工作方式与我预期的一样
请注意,我是这样设置代码的,因为我想阻止Run函数,直到条件为true,但我只想每隔一秒左右检查一次条件。在这种情况下,哪一个先发生并不重要_重置开始时没有标记,因此WaitOne将停止。一旦满足条件,它将被释放。如果满足条件并且在WaitOne调用之前释放了_reset,它将不会停止。这是否意味着我调用WaitOne并设置的顺序无关紧要?是的。它说得很对,我明白了。我很难弄清楚他们在MSDN AutoResetEvent页面上使用的术语。谢谢