标签:lease tab 名称 sleep 完成 win sys color ext
下面的代码展示了,限制同时访问数据库线程为5个。
using System; using System.Threading; namespace semaphoreSlim_Test { class Program { 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(); } Console.ReadKey(); } static SemaphoreSlim _semaphor = new SemaphoreSlim(4); static void AccessDatabase(string name,int seconds) { Console.WriteLine("{0} waits to access a database", name); _semaphor.Wait(); Console.WriteLine("{0} was granted an access to a database", name); Thread.Sleep(TimeSpan.FromSeconds(seconds)); Console.WriteLine("{0} is completed", name); _semaphor.Release(); } } }
标签:lease tab 名称 sleep 完成 win sys color ext
原文地址:https://www.cnblogs.com/gougou1981/p/12342203.html