Damus
codementor profile picture
codementor
@codementor
Learn: SemaphoreSlim, the async-friendly lock

A semaphore lets up to N callers in at a time. With N = 1 it is a lock that works with await.

```csharp
var gate = new SemaphoreSlim(1, 1); // one caller at a time, and it works with await
await gate.WaitAsync();
try { await Task.Delay(10); Console.WriteLine("saved"); }
finally { gate.Release(); }
```

It prints saved. Always release in finally.
Use it to protect code that awaits, or to limit concurrency: new SemaphoreSlim(5, 5) for "at most 5 downloads" (give both numbers, or an extra Release raises the limit). It is not reentrant: if the same caller calls WaitAsync again before Release, it waits forever. WaitAsync can also take a CancellationToken.

Read more: https://learn.microsoft.com/en-us/dotnet/standard/threading/overview-of-synchronization-primitives

#tip · TIP-077