AutoResetEvent
与ManualResetEvent的区别是,AutoResetEvent.WaitOne()会自动改变事件对象的状态,即AutoResetEvent.WaitOne() 执行完毕 自动进入 reset() 状态
gAutoResetEvent.Set(); //开启
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApp_ForTest
{
internal class Program
{
private static AutoResetEvent gAutoResetEvent = new AutoResetEvent(false);
static void Main(string[] args)
{
Thread t1 = new Thread(new ThreadStart(TestMethod));
t1.IsBackground = true;
t1.Start();
while(true)
{
if (Console.ReadKey().Key.ToString() == "C")
{
gAutoResetEvent.Set(); //开启
}
if (Console.ReadKey().Key.ToString() == "D")
{
gAutoResetEvent.Reset(); //阻塞
}
}
}
public static void TestMethod()
{
while(true)
{
gAutoResetEvent.WaitOne();
//Thread.Sleep(500);
Console.Write("HELLO ");
//gAutoResetEvent.Reset();
}
}
}
}
看看 输出