SemaphoreSlim
SemaphoreSlim хранит счётчик свободных допусков. Wait уменьшает его, Release - увеличивает.
Синтаксис
var sem = new SemaphoreSlim(1, 1);
Пример
Давайте захватим единственный допуск с таймаутом 0:
using System;
using System.Threading;
class Program
{
static void Main()
{
var sem = new SemaphoreSlim(1, 1);
bool first = sem.Wait(0);
bool second = sem.Wait(0);
Console.WriteLine(first);
Console.WriteLine(second);
Console.WriteLine(sem.CurrentCount);
sem.Release();
}
}
Результат выполнения кода:
True
False
0
Пример
Давайте создадим семафор с двумя допусками:
using System;
using System.Threading;
class Program
{
static void Main()
{
var sem = new SemaphoreSlim(2, 2);
Console.WriteLine(sem.CurrentCount);
}
}
Результат выполнения кода:
2
Смотрите также
-
Wait,
занять допуск -
Release,
вернуть допуск -
CurrentCount,
свободные места -
Monitor,
блокировка на объекте