I just started learning SemaphoreSlim
but how does the semaphore.CurrentCount increments and decrements in this program? From my understanding, when semaphore.Wait()
is called the release counter is decremented by 1 and when semaphore.Release()
, two threads are allowed to execute but how does the semaphore.CurrentCount
get incremented? does it start from 0 or 1 ?
var semaphore = new SemaphoreSlim(2, 10);
for (int i = 0; i < 20; i++)
{
Task.Factory.StartNew(() =>
{
Console.WriteLine("Entering task " + Task.CurrentId);
semaphore.Wait(); //releasecount--
Console.WriteLine("Processing task " + Task.CurrentId);
});
}
while (semaphore.CurrentCount <= 2)
{
Console.WriteLine("Semaphore count: " + semaphore.CurrentCount);
Console.ReadKey();
semaphore.Release(2);
}
Console.ReadKey();
Wait
decrements it andRelease
increments it.