ManualResetEvent
是 C# 中的一個同步原語,它允許一個或多個線程等待,直到另一個線程設(shè)置事件。要實現(xiàn)多線程協(xié)作,你可以使用 ManualResetEvent
來同步線程的執(zhí)行。
下面是一個簡單的示例,展示了如何使用 ManualResetEvent
實現(xiàn)兩個線程的協(xié)作:
using System;
using System.Threading;
class Program
{
static ManualResetEvent _event1 = new ManualResetEvent(false);
static ManualResetEvent _event2 = new ManualResetEvent(false);
static void Thread1()
{
Console.WriteLine("Thread1 開始執(zhí)行");
_event1.WaitOne(); // 等待線程2發(fā)出信號
Console.WriteLine("線程2已發(fā)出信號,Thread1繼續(xù)執(zhí)行");
_event2.Set(); // 設(shè)置事件,喚醒等待的線程3
Console.WriteLine("Thread1 已設(shè)置事件,線程3將被喚醒");
}
static void Thread2()
{
Console.WriteLine("Thread2 開始執(zhí)行");
Thread.Sleep(1000); // 模擬耗時操作
Console.WriteLine("Thread2 執(zhí)行完畢,準(zhǔn)備發(fā)出信號");
_event1.Set(); // 設(shè)置事件,喚醒等待的線程1
Console.WriteLine("Thread2 已設(shè)置事件,線程1將被喚醒");
}
static void Thread3()
{
Console.WriteLine("Thread3 開始執(zhí)行");
_event2.WaitOne(); // 等待線程1發(fā)出信號
Console.WriteLine("線程1已發(fā)出信號,Thread3繼續(xù)執(zhí)行");
Console.WriteLine("Thread3 執(zhí)行完畢");
}
static void Main(string[] args)
{
Thread thread1 = new Thread(new ThreadStart(Thread1));
Thread thread2 = new Thread(new ThreadStart(Thread2));
Thread thread3 = new Thread(new ThreadStart(Thread3));
thread1.Start();
thread2.Start();
thread3.Start();
thread1.Join();
thread2.Join();
thread3.Join();
Console.WriteLine("所有線程執(zhí)行完畢");
}
}
在這個示例中,我們創(chuàng)建了三個線程:Thread1
、Thread2
和 Thread3
。Thread1
和 Thread3
需要等待 Thread2
的信號才能繼續(xù)執(zhí)行,而 Thread2
在執(zhí)行完耗時操作后需要發(fā)出信號以喚醒 Thread1
。
我們使用兩個 ManualResetEvent
對象 _event1
和 _event2
來實現(xiàn)線程間的同步。_event1
用于同步 Thread1
和 Thread2
,_event2
用于同步 Thread2
和 Thread3
。
在 Thread1
和 Thread3
中,我們使用 WaitOne()
方法等待相應(yīng)的事件被設(shè)置。在 Thread2
中,我們使用 Set()
方法設(shè)置事件以喚醒等待的線程。
最后,在 Main
方法中,我們啟動這三個線程并等待它們執(zhí)行完畢。