C# Reference ยท Async and Concurrency
Mutex and SemaphoreSlim
Reference for Mutex, Semaphore and SemaphoreSlim in C#: limit concurrency, lock across await with WaitAsync, and choose between them.
A semaphore is a counter of permits. A thread calls Wait to take a permit (blocking if none is left) and Release to give it back. A semaphore created with one permit works as a mutual-exclusion lock; one created with N permits lets at most N callers in at once.
SemaphoreSlim is the lightweight in-process version and the only one with WaitAsync, so it is the right tool for limiting concurrency in async code. Mutex and Semaphore are heavier kernel objects that can be named and shared between processes.
var gate = new SemaphoreSlim(initialCount: 2); await gate.WaitAsync(); try { /* at most 2 callers here */ } finally { gate.Release(); }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
public class SemaphoreSlim : IDisposable { public SemaphoreSlim(int initialCount); public SemaphoreSlim(int initialCount, int maxCount); public int CurrentCount { get; } public void Wait(); public bool Wait(int millisecondsTimeout); public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken); public Task WaitAsync(); public Task<bool> WaitAsync(int millisecondsTimeout); public Task WaitAsync(CancellationToken cancellationToken); public int Release(); public int Release(int releaseCount); } public sealed class Mutex : WaitHandle { public Mutex(); public Mutex(bool initiallyOwned); public Mutex(bool initiallyOwned, string? name); public bool WaitOne(); public bool WaitOne(int millisecondsTimeout); public void ReleaseMutex(); }
| Name | Description |
|---|---|
initialCount |
Permits available at the start. |
maxCount |
Upper limit for permits; releasing beyond it throws. Default is int.MaxValue. |
millisecondsTimeout |
Maximum time to wait; 0 tests without blocking. |
name |
A system-wide name for a Mutex, used to share it between processes. |
Returns: Wait(int) and WaitOne(int) return true if the permit was taken. Release() returns the count before the release.
Errors: SemaphoreFullException when Release would exceed maxCount; ApplicationException when ReleaseMutex is called by a thread that does not own the mutex; ObjectDisposedException after Dispose.
Usage notes
- Always release in
finally. If the code betweenWaitandReleasethrows, the permit is lost and later callers wait forever. - Do not
Releaseafter a failed or canceledWait. Take the permit before thetryblock, as in the first example. SemaphoreSlimis not reentrant and has no owner. A thread that waits twice on a one-permit semaphore blocks itself, and any thread may callRelease.Mutexis reentrant and owned. It is for cross-process coordination (for example, a single-instance application with a named mutex). Its cost is a kernel transition per call; uselockfor ordinary in-process mutual exclusion.- Named mutexes and semaphores are visible to other processes by name; on Linux and macOS named objects are implemented with files and have limits. They are not testable in our sandbox.
- No fairness guarantee. Waiters are not guaranteed to be served in the order they arrived.
- Dispose a
SemaphoreSlimonly when you useAvailableWaitHandle; otherwise disposal is optional but harmless once nobody waits. - Throttling tip. A semaphore around a call to an external service is the usual way to cap parallel requests. For parallel loops,
ParallelOptions.MaxDegreeOfParallelismis simpler; see Parallel.ForEachAsync.