/设置同时访问线程最大数量 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才能执行后面的代码
Asp.Net Core 实现异步操作锁 (SemaphoreSlim)
发布时间 2023-07-18 17:29:19作者: wtt123