Why this SemaphoreSlim waits indefinitely?

using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            Task.Run(Test);
            Console.ReadKey();
        }

        public static async Task Test()
        {
            var semahore = new SemaphoreSlim(0, 1);
            Console.WriteLine("before");
            await semahore.WaitAsync();
            Console.WriteLine("after");
        }
    }
}

I create a semaphore with limit 1 and current value of 0. It should allow 1 thread to pass, right? Why it doesn't in this example?

Jon Skeet
people
quotationmark

I create a semaphore with limit 1 and current value of 0. It should allow 1 thread to pass, right?

No - the current value is 0, exactly as you wrote.

Semaphore values count down when they're awaited - the count is effectively "the number of tokens available to be acquired". From the docs:

The count is decremented each time a thread enters the semaphore, and incremented each time a thread releases the semaphore. To enter the semaphore, a thread calls one of the Wait or WaitAsync overloads. To release the semaphore, it calls one of the Release overloads. When the count reaches zero, subsequent calls to one of the Wait methods block until other threads release the semaphore.

If you want to create a semaphore which will immediately allow one thread to wait for it and "pass", you should create it with an initial value of 1, not 0.

people

See more on this question at Stackoverflow