AutoResetEvent 常常被用来在两个线程之间进行信号发送,是.net线程简易同步方法中的一种。 两个线程共享相同的AutoResetEvent对象,线程可以通过调用AutoResetEvent对象的WaitOne()方法进入等待状态,然后另外一个线程通过调用AutoResetEvent对象的Set()方法取消等待的状态。
1.对象实例化
AutoResetEvent autoResetEvent = new AutoResetEvent(false);
2.WaitOne 方法
阻止当前线程继续运行,等待其他线程发送信号,收到信号后将返回True,否则将返回False。
if(autoResetEvent.WaitOne(5000))
{
MessageBox.Show(“go on”);
}
else
{
MessageBox.Show(“5s 超时。”);
}
3.Set 方法
其他线程的结束信号,发送给阻塞线程。
demo如下:主线程计算1-100 的和,当累加到50时阻止主线程,当thread()执行后主线程继续执行。
private static AutoResetEvent autoResetEvent = new AutoResetEvent(false);
void run()
{
int i=0;
int sum=0;
for(i=0;i<100;i++)
{
sum+=i;
if(sum==55)
{
if(autoResetEvent.WaitOne==3000)
{
MessageBox.Show("Go on");
}
else
{
MessageBox.Show("time out ");
break;
}
}
}
}
void thread()
{
autoResetEvent .set();
}