class Program { private const int InitialCount = 2; private const int MaximumCount = 8; static void Main() { var semaphoreObject = new SemaphoreSlim(InitialCount, MaximumCount); var printerObject = new Printer(); for (int i = 0; i < 20; ++i) { int j = i; Task.Factory.StartNew(() => { Request(semaphoreObject); printerObject.Print(j); Release(semaphoreObject); NumberAvailable(semaphoreObject); }); } Console.ReadLine(); } private static void Request(SemaphoreSlim s) { s.Wait(); } private static void Release(SemaphoreSlim s) { s.Release(); } private static void NumberAvailable(SemaphoreSlim s) { Console.WriteLine($"Available resource: {s.CurrentCount}"); } } class Printer { public void Print(int documentToPrint) { Console.WriteLine("Printing document: " + documentToPrint); Thread.Sleep(TimeSpan.FromSeconds(5)); } }
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)