I have a simple test code here with SemaphoreSlim
static SemaphoreSlim mSemaphore = new SemaphoreSlim(3);
static async Task Main()
{
var tasks = new Task[5];
for (var i = 0; i < tasks.Length; i++)
{
var taskNo = i;
tasks[i] = Task.Run(() => DoWork($"task{taskNo}"));
}
await Task.WhenAll(tasks);
}
static async Task DoWork(string taskName)
{
for (var i = 0; i < 3; i++)
{
mSemaphore.Wait();
Console.WriteLine($"{taskName}: doing {i}.");
await Task.Delay(1000);
mSemaphore.Release();
}
}
if i am correct: in my context my Semaphore should allow only 3 Tasks to do their work, and then it should release them, and after that it should let my other 2 Tasks to do their job.
The Problem
i tested this out but unfortunately sometimes i get different/wrong results.
here are 2 output results.
OUTPUT
