个人理解这个应该就相当于一个旗标,在不同线程之间创建一个都可以使用的bool量
AutoResetEvent 常常被用来在两个线程之间进行信号发送,两个线程共享相同的AutoResetEvent对象,线程可以通过调用AutoResetEvent对象的WaitOne()方法进入等待状态,waitone可以有一个等待时间参数,然后另外一个线程通过调用AutoResetEvent对象的Set()方法取消等待的状态,通过reset()恢复
class Program
{
const int count = 10;
//赋值为false也就是没有信号
static AutoResetEvent myResetEvent = new AutoResetEvent(false);
static int number;
static void Main(string[] args)
{
Thread thread = new Thread(funThread);
thread.Name = "QQ";
thread.Start();
for (int i = 1; i < count; i++)
{
Console.WriteLine("first number: {0}",i);
number = i;
//这里是设置为有信号
myResetEvent.Set();
Thread.Sleep(2000);
}
thread.Abort();
}
static void funThread()
{
while (true)
{
//执行到这个地方时,会等待set调用后改变了信号才接着执行
myResetEvent.WaitOne();
Console.WriteLine("end {0} number: {1}", Thread.CurrentThread.Name, number);
}
}
}
ManualResetEvent的使用和效果和AutoResetEvent是一样的,不同的是AutoResetEvent set后,当某个线程里有waitone接受后,autorestevent又变成set之前的状态,即其他线程的waitone仍在等待,而manualrestevent set之后,其他线程的waitone都不在等待,除非手动调用manualresetevent的Reset()。