Skip to content
Tutorials Center
My learning

Topics

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.

C#
var gate = new SemaphoreSlim(initialCount: 2);
await gate.WaitAsync();
try { /* at most 2 callers here */ }
finally { gate.Release(); }

Try it

C# Limiting concurrency with SemaphoreSlim

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.

C# Timeouts, maximum count and Mutex

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

C#
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 between Wait and Release throws, the permit is lost and later callers wait forever.
  • Do not Release after a failed or canceled Wait. Take the permit before the try block, as in the first example.
  • SemaphoreSlim is not reentrant and has no owner. A thread that waits twice on a one-permit semaphore blocks itself, and any thread may call Release.
  • Mutex is 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; use lock for 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 SemaphoreSlim only when you use AvailableWaitHandle; 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.MaxDegreeOfParallelism is simpler; see Parallel.ForEachAsync.