/设置同时访问线程最大数量 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(); } }标签:Core,Asp,SemaphoreSlim,name,int,线程,semaphore,Console From: https://www.cnblogs.com/wangtiantian/p/17563617.html
上面的代码new
了一个SemaphoreSlim
对象,设置访问线程最大数量为4
,开启5
个线程,发现,线程5
一开始一直处于等待状态,直到线程1
完成了,调用了_semaphore.Release()
释放,线程5
才能执行后面的代码