using System.Threading.Tasks;
private static SemaphoreSlim semaphore;
private static int padding;
public static void Main()
semaphore = new SemaphoreSlim(0, 3);
Console.WriteLine("{0} tasks can enter the semaphore.", semaphore.CurrentCount);
Task[] tasks = new Task[5];
for (int i = 0; i < 5; i++)
tasks[i] = Task.Run(() =>
Console.WriteLine("Task {0} begins and waits for the semaphore.", Task.CurrentId);
Interlocked.Add(ref padding, 100);
Console.WriteLine("Task {0} enters the semaphore.", Task.CurrentId);
Thread.Sleep(1000 + padding);
semaphoreCount = semaphore.Release();
Console.WriteLine("Task {0} releases the semaphore; previous count: {1}.", Task.CurrentId, semaphoreCount);
Console.WriteLine("Main thread calls Release(3) --> 3 tasks can enter Semaphore");
Console.WriteLine("Main thread exits.");