Home > OS >  Setting C# SemaphoreSlim minimum count does not seem to work
Setting C# SemaphoreSlim minimum count does not seem to work

Time:10-10

Here is my code

   SemaphoreSlim slim = new SemaphoreSlim(1);
            _ = Task.Run(() =>
            {
                Task.Delay(2000);
                _testOutputHelper.WriteLine("Unleash!");
                slim.Release();
            });
            _testOutputHelper.WriteLine("Waiting");
            await slim.WaitAsync();
            _testOutputHelper.WriteLine("Done");

The output is ironically as follows:

Waiting
Unleash!
Done

AFAIK WaitAsync() is suppose to allow the thread since I've set initial count as 1. Somehow it's not behaving that way

Any help?

CodePudding user response:

You forgot to await your Task.Delay(2000), so this line basically does nothing and Task.Run thread immediately goes and writes "Unleash!", then releases semaphore. So to achieve what you want, just await that delay, giving main thread time to reach WaitAsync first:

SemaphoreSlim slim = new SemaphoreSlim(1);
_ = Task.Run(async () =>
{
    await Task.Delay(2000);
    Console.WriteLine("Unleash!");
    slim.Release();
});
Console.WriteLine("Waiting");
await slim.WaitAsync();
Console.WriteLine("Done");
  • Related