c#并发semaphoreslim

该类限制了用时访问同一资源的线程数量,下面写一段代码来讲解他的用法

class Program
{
static SemaphoreSlim _semaphore = new SemaphoreSlim(4);
static void acquireSemaphore(string name, int seconds)
{
Console.WriteLine("{0} wait",name);
_semaphore.Wait();
Console.WriteLine("{0} access",name);
Thread.Sleep(TimeSpan.FromSeconds(seconds));
Console.WriteLine("{0} Release", name);
_semaphore.Release();
}
static void Main(string[] args)
{
for(int i = 1; i <= 6; i++)
{
string threadName = "thread" + i;
int secondsToWait = 2 + 2 * i;
var t = new Thread(() => acquireSemaphore(threadName, secondsToWait));
t.Start();
}
Console.ReadKey();
这里我写了一个函数来获取SemaphoreSlim 信号量,在创建时static SemaphoreSlim _semaphore = new SemaphoreSlim(4);设置可以同时访问的线程数为4,也就是说运行后的情况应该是在线程1、2、3、4访问该信号量没有释放之前,线程5会一直处于等待状态,下面我们运行一下看看结果。

从运行结果我们可以看到,线程5,6处于等待状态,直到1释放5获得信号量,2释放6获得信号量。
---------------------
作者:Maybe_ch
来源:CSDN
原文:https://blog.csdn.net/Maybe_ch/article/details/84818373
版权声明:本文为博主原创文章,转载请附上博文链接!

原文地址:https://www.cnblogs.com/hj558558/p/10080251.html