编程语言
首页 > 编程语言> > C#线程同步SemaphoreSlim类介绍

C#线程同步SemaphoreSlim类介绍

作者:互联网

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         }

运行结果:

 

标签:SemaphoreSlim,name,C#,Console,semaphoreSlim,线程,WriteLine,static
来源: https://www.cnblogs.com/yangda/p/12587345.html