If you want to block while the value is 0, you will need additional synchronization for this. I think the right solution for you is SemaphoreSlim
, because it does exactly what you need: waiting while its value is 0.
With that, the code would look something like:
SemaphoreSlim slotsSemaphore = new SemaphoreSlim(…);
…
foreach (var job in JobQueue.GetConsumingEnumerable())
{
slotsSemaphore.Wait();
JobHandler jobHandler = job;
Task.Factory.StartNew(() =>
{
try
{
ExecuteJob(jobHandler);
}
finally
{
slotsSemaphore.Release();
}
});
}