ManualResetEvent
是 C# 中一种用于同步线程的类,它允许一个或多个线程等待某个条件成立。它可以与其他同步机制结合使用,例如 Mutex
、AutoResetEvent
和 SemaphoreSlim
等。下面是一些示例,展示了如何将 ManualResetEvent
与其他同步机制结合使用。
Mutex
使用:using System;
using System.Threading;
class Program
{
static Mutex mutex = new Mutex();
static ManualResetEvent resetEvent = new ManualResetEvent(false);
static void Main()
{
Thread t1 = new Thread(ThreadMethod1);
Thread t2 = new Thread(ThreadMethod2);
t1.Start();
t2.Start();
t1.Join();
t2.Join();
}
static void ThreadMethod1()
{
mutex.WaitOne(); // 获取互斥锁
Console.WriteLine("Thread 1 acquired the lock.");
resetEvent.Set(); // 设置手动重置事件
mutex.ReleaseMutex(); // 释放互斥锁
}
static void ThreadMethod2()
{
resetEvent.WaitOne(); // 等待手动重置事件
Console.WriteLine("Thread 2 acquired the event.");
mutex.WaitOne(); // 获取互斥锁
Console.WriteLine("Thread 2 acquired the lock.");
mutex.ReleaseMutex(); // 释放互斥锁
}
}
AutoResetEvent
使用:using System;
using System.Threading;
class Program
{
static AutoResetEvent autoResetEvent = new AutoResetEvent(false);
static object lockObject = new object();
static void Main()
{
Thread t1 = new Thread(ThreadMethod1);
Thread t2 = new Thread(ThreadMethod2);
t1.Start();
t2.Start();
t1.Join();
t2.Join();
}
static void ThreadMethod1()
{
autoResetEvent.WaitOne(); // 等待自动重置事件
lock (lockObject)
{
Console.WriteLine("Thread 1 acquired the lock.");
}
autoResetEvent.Set(); // 设置自动重置事件
}
static void ThreadMethod2()
{
autoResetEvent.WaitOne(); // 等待自动重置事件
lock (lockObject)
{
Console.WriteLine("Thread 2 acquired the lock.");
}
autoResetEvent.Set(); // 设置自动重置事件
}
}
SemaphoreSlim
使用:using System;
using System.Threading;
class Program
{
static SemaphoreSlim semaphore = new SemaphoreSlim(1, 1);
static object lockObject = new object();
static void Main()
{
Thread t1 = new Thread(ThreadMethod1);
Thread t2 = new Thread(ThreadMethod2);
t1.Start();
t2.Start();
t1.Join();
t2.Join();
}
static void ThreadMethod1()
{
semaphore.Wait(); // 等待信号量
lock (lockObject)
{
Console.WriteLine("Thread 1 acquired the lock.");
}
semaphore.Release(); // 释放信号量
}
static void ThreadMethod2()
{
semaphore.Wait(); // 等待信号量
lock (lockObject)
{
Console.WriteLine("Thread 2 acquired the lock.");
}
semaphore.Release(); // 释放信号量
}
}
这些示例展示了如何将 ManualResetEvent
与其他同步机制结合使用,以确保线程安全地访问共享资源。在实际应用中,你可以根据需要选择合适的同步机制。