多线程编程学习系列之--SemaphoreSlim类

示例代码

//设置同时访问线程最大数量
static SemaphoreSlim _semaphore = new SemaphoreSlim(4);

static void AccessDatabase(string name, int seconds)
{
   Console.WriteLine($"{name} waits to access a database");
   _semaphore.Wait();
   Console.WriteLine($"{name} was granted an access to a database");
   Thread.Sleep(TimeSpan.FromSeconds(seconds));
   Console.WriteLine($"{name} is completed");
   _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(() => AccessDatabase(threadName, secondsToWait));
       t.Start();
   }
}

结果:
在这里插入图片描述
原理
new 了一个SemaphoreSlim 对象,设置访问线程最大数量为4,开启5个线程,发现,线程5一开始一直处于等待状态,直到线程1完成了,调用了_semaphore.Release()释放,线程5才能执行后面的代码。

发布了37 篇原创文章 · 获赞 3 · 访问量 6330

猜你喜欢

转载自blog.csdn.net/huan13479195089/article/details/88947313