温馨提示×

如何在C#中使用ManualResetEvent

c#
小樊
82
2024-07-02 20:02:14
栏目: 编程语言

在C#中,可以使用ManualResetEvent类来实现线程间的同步和通信。下面是一个简单的示例代码,演示如何在C#中使用ManualResetEvent:

using System;
using System.Threading;

class Program
{
    static ManualResetEvent manualResetEvent = new ManualResetEvent(false);

    static void Main(string[] args)
    {
        Thread thread1 = new Thread(() =>
        {
            Console.WriteLine("Thread 1 is waiting...");
            manualResetEvent.WaitOne();

            Console.WriteLine("Thread 1 is now running.");
        });

        Thread thread2 = new Thread(() =>
        {
            Console.WriteLine("Thread 2 is waiting...");
            manualResetEvent.WaitOne();

            Console.WriteLine("Thread 2 is now running.");
        });

        thread1.Start();
        thread2.Start();

        Thread.Sleep(2000); // 等待2秒钟

        manualResetEvent.Set(); // 发信号,让等待的线程继续执行

        thread1.Join();
        thread2.Join();
    }
}

在上面的示例代码中,我们创建了一个ManualResetEvent实例并初始化为false。然后创建了两个线程(thread1和thread2),它们都在等待ManualResetEvent对象的信号。在主线程中等待2秒钟后,调用Set方法发送信号,让等待的线程继续执行。

需要注意的是,ManualResetEvent对象在调用Set方法后会一直保持信号状态,直到调用Reset方法将其重新设置为非信号状态。

0