AutoResetEvent 是 C# 中一种用于多线程同步的类,它位于 System.Threading 命名空间中。AutoResetEvent 允许一个或多个线程等待其他线程完成操作。它在多线程编程中的作用主要体现在以下几个方面:
同步:AutoResetEvent 可以用于确保某些线程在继续执行之前等待其他线程完成特定任务。例如,当一个线程完成了对共享资源的访问,它可以通过调用 AutoResetEvent.Set() 方法来通知其他等待的线程可以继续执行。
互斥:AutoResetEvent 可以用于实现互斥锁(Mutex),确保同一时间只有一个线程可以访问共享资源。当一个线程获得锁时,其他线程必须等待直到锁被释放。
事件通知:AutoResetEvent 可以用于实现事件通知机制。当一个线程完成特定任务时,它可以调用 AutoResetEvent.Set() 方法来触发一个事件,通知其他等待的线程。
下面是一个简单的 AutoResetEvent 示例:
using System; using System.Threading; class Program { static AutoResetEvent _autoResetEvent = new AutoResetEvent(false); // 初始状态为 false static void Main() { Thread thread1 = new Thread(Thread1); Thread thread2 = new Thread(Thread2); thread1.Start(); thread2.Start(); thread1.Join(); thread2.Join(); } static void Thread1() { Console.WriteLine("Thread 1 is waiting for the AutoResetEvent."); _autoResetEvent.WaitOne(); // 等待事件被触发 Console.WriteLine("Thread 1 has been notified."); } static void Thread2() { Console.WriteLine("Thread 2 is setting the AutoResetEvent."); _autoResetEvent.Set(); // 触发事件 Console.WriteLine("Thread 2 has set the AutoResetEvent."); } } 在这个示例中,Thread1 等待 _autoResetEvent 被触发,而 Thread2 在完成特定任务后触发该事件。这样,我们可以确保 Thread1 在 Thread2 完成任务之前不会继续执行。