在C#中,AutoResetEvent是一个同步原语,用于在多个线程之间进行通信
using System; using System.Threading; class Program { static AutoResetEvent autoResetEvent = new AutoResetEvent(false); // 初始状态为false static void Main() { Thread thread1 = new Thread(Thread1Method); Thread thread2 = new Thread(Thread2Method); thread1.Start(); thread2.Start(); thread1.Join(); thread2.Join(); } static void Thread1Method() { Console.WriteLine("Thread 1 is waiting for the AutoResetEvent."); autoResetEvent.WaitOne(); // 等待事件被设置为true Console.WriteLine("Thread 1 has been signaled."); } static void Thread2Method() { Thread.Sleep(1000); // 让线程2睡眠1秒,以便在线程1之前执行 Console.WriteLine("Thread 2 is signaling the AutoResetEvent."); autoResetEvent.Set(); // 将事件设置为true } } 在这个示例中,我们创建了一个名为autoResetEvent的AutoResetEvent实例,并将其初始状态设置为false。然后,我们创建了两个线程thread1和thread2,分别执行Thread1Method和Thread2Method方法。
在Thread1Method中,我们使用autoResetEvent.WaitOne()等待事件被设置为true。在Thread2Method中,我们首先让线程睡眠1秒,然后使用autoResetEvent.Set()将事件设置为true。当事件被设置为true时,Thread1Method将继续执行。