該類限制了用時訪問同一資源的線程數量,下面寫一段代碼來講解他的用法
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
版權聲明:本文為博主原創文章,轉載請附上博文鏈接!