AutoREsetEvent的Set和Reset方法:
Set:发出一个释放信号,给最先被此对象阻塞的线程。
Reset:在没有线程被阻塞的情况下释放出了Set信号,下个线程在用到Waitone方法时将不会被阻塞,用此方法可以将状态置为阻塞,初始化为不阻塞,也可使用此方法重设。
重点
1.AutoResetEvent初始化时,参数设置表示其第一次的使用是否已经是阻塞状态,true表示线程不等待,false表示线程需要等待。
2.每次调用AutoResetEvent的set方法将只会释放一个被阻止的线程,不会同时释放所有被此阻塞的线程。
3.AutoResetEvent的waitone方法不带参数将无休止等待一个被释放的信号,直到收到信号才继续执行。
4.带参数表示使用的参数为等待的时间,在等待时间内收到释放信号将返回一个true并继续执行,在参数设定的时间内没收到信号将返回false并继续向下执行。
class Program
{
private static AutoResetEvent event_1 = new AutoResetEvent(true);
private static AutoResetEvent event_2 = new AutoResetEvent(false);
static AutoResetEvent autoReset = new AutoResetEvent(true);
static void Main(string[] args)
{
//Console.WriteLine("Press Enter to create three threads and start them.\r\n" +
// "The threads wait on AutoResetEvent #1, which was created\r\n" +
// "in the signaled state, so the first thread is released.\r\n" +
// "This puts AutoResetEvent #1 into the unsignaled state.");
//Console.ReadLine();
//for (int i = 1; i < 4; i++)
//{
// Thread t = new Thread(ThreadProc);
// t.Name = "Thread_" + i;
// t.Start();
//}
//Thread.Sleep(250);
//for (int i = 0; i < 2; i++)
//{
// Console.WriteLine("Press Enter to release another thread.");
// Console.ReadLine();
// event_1.Set();
// Thread.Sleep(250);
//}
//Console.WriteLine("\r\nAll threads are now waiting on AutoResetEvent #2.");
//for (int i = 0; i < 3; i++)
//{
// Console.WriteLine("Press Enter to release a thread.");
// Console.ReadLine();
// event_2.Set();
// Thread.Sleep(250);
//}
Thread thread1=new Thread(Got);
Thread thread2=new Thread(SetState);
thread1.Start();
thread2.Start();
// Console.WriteLine("read a key");
Console.ReadLine();
autoReset.Set();
Console.Read();
}
static void Got()
{
autoReset.Reset();
Console.WriteLine("start..." + DateTime.Now.Second);
var b = autoReset.WaitOne();
Console.WriteLine("等待完成" + DateTime.Now.Second);
Console.WriteLine("在等待一次"+DateTime.Now.Second);
autoReset.WaitOne();
Console.WriteLine("等待完成"+DateTime.Now.Second);
if (b)
{
Console.WriteLine("五秒之内已经释放没柱塞");
Console.Read();
}
else
{
Console.WriteLine("没释放柱塞");
Console.Read();
}
}
static void SetState()
{
Console.WriteLine("等两秒再设置");
Thread.Sleep(2000);
autoReset.Set();
}
void SetEvent()
{
Task.Run((() =>
{
Thread.Sleep(2000);
Console.WriteLine("两秒等待完成"+DateTime.Now.Second);
autoReset.Set();
Thread.Sleep(2000);
autoReset.Set();
}));
}
static void ThreadProc()
{
string name = Thread.CurrentThread.Name;
Console.WriteLine("{0} waits on AutoResetEvent #1.", name);
event_1.WaitOne();
Console.WriteLine("{0} is released from AutoResetEvent #1.", name);
Console.WriteLine("{0} waits on AutoResetEvent #2.", name);
event_2.WaitOne();
Console.WriteLine("{0} is released from AutoResetEvent #2.", name);
Console.WriteLine("{0} ends.", name);
}
}
代码下载