SemaphoreSlim類限制了同時訪問一個資源的線程數量
代碼如下:
1 static SemaphoreSlim semaphoreSlim = new SemaphoreSlim(4); 2 3 static void AccessDatabase(string name, int seconds) 4 { 5 Console.WriteLine($"{name}等待訪問數據庫"); 6 semaphoreSlim.Wait(); 7 Console.WriteLine($"{name}被授權訪問數據庫"); 8 Thread.Sleep(TimeSpan.FromSeconds(seconds)); 9 Console.WriteLine($"{name}訪問數據庫已經完成"); 10 semaphoreSlim.Release(); 11 } 12 13 static void Main(string[] args) 14 { 15 for (int i = 1; i <= 6; i++) 16 { 17 string threadName = $"線程{i}"; 18 int secondsToWait = 2 + 2 * i; 19 var t = new Thread(() => AccessDatabase(threadName, secondsToWait)); 20 t.Start(); 21 } 22 Console.ReadLine(); 23 }
運行結果: