c#

c# autoresetevent如何创建

小樊
88
2024-11-18 11:07:03
栏目: 编程语言

在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(); // 将事件设置为有信号状态
    }
}

在这个示例中,我们创建了两个线程 thread1thread2Thread1Method 方法等待 AutoResetEvent 变为有信号状态,然后继续执行。Thread2Method 方法在休眠1秒后,将 AutoResetEvent 设置为有信号状态,从而唤醒等待的线程。

0
看了该问题的人还看了