如何在C#中使用ManualResetEvent

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

在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方法将其重新设置为非信号状态。

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号