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         }

运行结果:

C#线程同步SemaphoreSlim类介绍

 

相关文章:

  • 2021-09-01
  • 2021-11-08
  • 2022-12-23
  • 2021-05-27
  • 2022-01-19
  • 2021-06-20
猜你喜欢
  • 2022-02-27
  • 2022-12-23
  • 2022-02-19
  • 2022-02-04
  • 2021-11-24
  • 2022-01-19
  • 2022-12-23
相关资源
相似解决方案