可用来限制同时访问某个资源的线程数量。
示例
using System;
using System.Threading;
namespace SemaphoreTest
{
class Program
{
static SimpleWaitLock slock;
static void Main(string[] args)
{
//允许2条线程同时访问资源
slock = new SimpleWaitLock(2, 10);
Thread myThread;
for (int i = 0; i < 10; i++)
{
myThread = new Thread(new ThreadStart(MyThreadProc));
myThread.Name = String.Format("Thread{0}", i + 1);
myThread.Start();
}
Console.ReadKey();
}
private static void MyThreadProc()
{
slock.Enter();
}
}
public sealed class SimpleWaitLock : IDisposable
{
private Semaphore m_available;
public SimpleWaitLock(int initialCount, int maximumCount)
{
m_available = new Semaphore(initialCount, maximumCount);
}
public void Enter()
{
m_available.WaitOne();//信号量减1
Console.WriteLine("{0} Thread Enter", Thread.CurrentThread.Name);
//模拟做些事情
Thread.Sleep(1000);
Leave();
}
public void Leave()
{
m_available.Release();//信号量加1
Console.WriteLine("{0} Thread Level", Thread.CurrentThread.Name);
}
public void Dispose() { }
}
}
运行测试