阅读量:2
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 与其他同步机制结合使用,以确保线程安全地访问共享资源。在实际应用中,你可以根据需要选择合适的同步机制。
以上就是关于“c# manualresetevent 如何与其他同步机制结合”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm