我剛開始學習SemaphoreSlim
但是在這個程序中semaphore.CurrentCount是如何增加和減少的呢?據我瞭解,當調用semaphore.Wait()
時,釋放計數器遞減1,當semaphore.Release()
時,允許執行兩個線程,但semaphore.CurrentCount
如何遞增?它是從0還是1開始的?semaphore.CurrentCount在這種情況下如何工作?
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();