C# Concurrency lesson – SemaphoreSlim
In Windows we have two types of semaphores, local and named system semaphores.
You can think of a semaphore as a bouncer in a nightclub, the responsibility is to only allow a number of people into the club at any one time.
.NET has a lightweight semaphore, ‘SemaphoreSlim’ that can be used for local communication (that is to say, system synchronization is not supported).
If you run the code above (e.g. in a .NET Core 2.1 project) you will be presented with the following result.
What is happening is that all the tasks try to get access to the semaphore, they are all initially blocked until
semaphore.Release(3);
is called which allows 3 tasks to enter at any one time.