阅读量:3
在C#中,AutoResetEvent 是一个同步原语,用于在多个线程之间进行通信。它可以用于控制对共享资源的访问,或者让一个或多个线程等待其他线程完成操作。要创建一个 AutoResetEvent,可以使用 new AutoResetEvent(bool) 构造函数,其中 bool 参数表示初始状态。如果设置为 true,则事件处于有信号状态;如果设置为 false,则事件处于无信号状态。
以下是一个简单的示例:
using System;
using System.Threading;
class Program
{
static AutoResetEvent autoResetEvent = new AutoResetEvent(false); // 创建一个初始状态为无信号的 AutoResetEvent
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(); // 等待事件变为有信号状态
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(); // 将事件设置为有信号状态
}
}
在这个示例中,我们创建了两个线程 thread1 和 thread2。Thread1Method 方法等待 AutoResetEvent 变为有信号状态,然后继续执行。Thread2Method 方法在休眠1秒后,将 AutoResetEvent 设置为有信号状态,从而唤醒等待的线程。
以上就是关于“c# autoresetevent如何创建”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm