AutoResetEvent
是 C# 中的一个同步原语,它允许一个或多个线程等待,直到另一个线程发出信号
以下是如何在 C# 中使用 AutoResetEvent
的示例:
AutoResetEvent
实例。你可以将其初始化为 true
或 false
。通常,将其初始化为 true
表示事件已经发出,等待的线程可以立即继续执行。AutoResetEvent autoResetEvent = new AutoResetEvent(true);
WaitOne()
方法等待事件发出信号。这个方法会阻塞当前线程,直到事件变为 false
。autoResetEvent.WaitOne();
Set()
方法将事件设置为 false
。这将允许等待的线程继续执行。如果事件已经是 false
,则 Set()
方法不会产生任何影响。autoResetEvent.Set();
true
,以便其他等待的线程可以继续执行,可以使用 Reset()
方法。autoResetEvent.Reset();
下面是一个简单的示例,展示了如何使用 AutoResetEvent
控制线程的执行顺序:
using System;
using System.Threading;
class Program
{
static AutoResetEvent autoResetEvent = new AutoResetEvent(true);
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 waiting for event...");
autoResetEvent.WaitOne(); // Wait for the event to be set
Console.WriteLine("Thread 1: Event received, continuing execution.");
}
static void Thread2()
{
Thread.Sleep(1000); // Simulate some work
Console.WriteLine("Thread 2 setting the event...");
autoResetEvent.Set(); // Set the event, allowing Thread 1 to continue
}
}
在这个示例中,Thread1
首先等待事件被设置。Thread2
在模拟一些工作之后设置事件,从而允许 Thread1
继续执行。