C# Interview Question #112
What is SemaphoreSlim, and when is it useful?
Concurrency, Performance & Design Senior Advanced
Quick Interview Answer
SemaphoreSlim limits how many callers can enter a protected region concurrently. Unlike lock, it can allow more than one caller and supports asynchronous waiting through WaitAsync.
Detailed Explanation
SemaphoreSlim limits how many callers can enter a protected region concurrently. Unlike lock, it can allow more than one caller and supports asynchronous waiting through WaitAsync.
It is useful for throttling access to limited resources, preventing duplicate asynchronous work, or serializing an async operation.
WaitAsync should normally be paired with Release in a finally block so the semaphore is released even when an exception occurs.
Code Example
private readonly SemaphoreSlim _gate = new(1, 1);
public async Task UpdateAsync()
{
await _gate.WaitAsync();
try
{
await SaveChangesAsync();
}
finally
{
_gate.Release();
}
}