AutoResetEvent 自动重置锁
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace AutoResetEventDemo
{
class Program
{
//static AutoResetEvent areLock = new AutoResetEvent(true);
//设置IsRealse为true
static AutoResetEvent areLock = new AutoResetEvent(true);
static void Main(string[] args)
{
//areLock.WaitOne(); //塞一张火车票到闸机中 =》 mainthread
//Console.WriteLine("火车票检验通过,可以通行");
//areLock.Set(); //从闸机中取火车票
//Console.ReadKey();
#region 新的累加
#endregion
//比如开启5个task
for (int i = 0; i < 5; i++)
{
Task.Factory.StartNew(() =>
{
Run();
});
}
Thread.Sleep(5000); //5s中之后,火车开走了,这个时候就要撤销栅栏
areLock.Set();
Console.Read();
}
static int nums = 0;
static void Run()
{
for (int i = 0; i < 10; i++)
{
try
{
//waitOne只有IsRealse为true的时候会继续往下执行,否则线程会进入等待队列
//AutoResetEvent会将IsRealse重置为false
//AutoResetEvent的线程队列只能有一个
areLock.WaitOne();
Console.WriteLine(nums++);
//areLock.Set();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
}
}
}
}
}