SemaphoreSlim class limits the number of threads simultaneously access a resource
code show as below:
. 1 static SemaphoreSlim SemaphoreSlim = new new SemaphoreSlim ( . 4 ); 2 . 3 static void AccessDatabase ( String name, int seconds The) . 4 { . 5 Console.WriteLine ($ " {name} waiting for access to the database " ); . 6 semaphoreSlim.Wait (); . 7 Console .WriteLine ($ " {} is authorized to access the database name " ); . 8 the Thread.Sleep (TimeSpan.FromSeconds (seconds the)); . 9 Console.WriteLine ($ "{name} has finished accessing the database " ); 10 semaphoreSlim.Release (); . 11 } 12 is 13 is static void the Main ( String [] args) 14 { 15 for ( int I = . 1 ; I <= . 6 ; I ++ ) 16 { . 17 String threadName $ = " thread} I { " ; 18 is int SecondsToWait = 2 + 2 * I; . 19 var T = new new Thread(() => AccessDatabase(threadName, secondsToWait)); 20 t.Start(); 21 } 22 Console.ReadLine(); 23 }
operation result: