Codectionary / Developer documentation / C#

Limit Async Access with SemaphoreSlim

Pair successful asynchronous waits with releases and avoid treating cancellation as an acquired slot.

Read the syntax

Pair successful asynchronous waits with releases and avoid treating cancellation as an acquired slot.

Work B cannot enter while A holds that slot; the finally returns it after A prints its exit.

What it is and why to use it

An application may need only one operation at a time, or at most a small number, inside a shared section. SemaphoreSlim provides an in-process count of available slots. WaitAsync waits asynchronously for a slot, and Release returns it. It is not a distributed lock and does not coordinate independent processes.

How it works

For a one-slot gate, construct SemaphoreSlim(1, 1). Await entry before entering a try/finally that releases the acquired slot. If a wait is cancelled before acquisition, do not release a slot that was never acquired. Dispose the semaphore only after all operations using it have finished. Fairness or strict FIFO admission is not guaranteed.

Common mistakes and limitations

Do not Release unconditionally when a wait may have failed. Do not hold a gate longer than the actual protected operation needs. Do not assume gated code is automatically safe against every other access path; all relevant operations must follow the same ownership protocol.

Run the examples locally

These complete Program.cs examples use a .NET 10 console project with the C# language version set to 12.0, nullable checking enabled and implicit usings disabled. They use standard .NET libraries and need no extra NuGet packages. This is the verified environment, not a claim that every API requires .NET 10 or works unchanged in .NET Framework, Unity or other runtimes.

Install a supported .NET 10 SDK, create the console project, replace its project file with the settings below, then replace Program.cs with one complete example at a time. Build and run from the project folder. using directives bring namespaces into scope; top-level statements form the program’s entry point, and any helper types follow those statements. Console.WriteLine writes terminal output. Do not combine examples that declare the same type names.

C# in Codectionary’s Playground is editing-only: it does not compile or execute these programs. Run them with the local .NET SDK to reproduce the expected output. Async examples use controlled in-process operations rather than live network services or timing-sensitive delays.

Create and enter a project

dotnet new console -n CSharpExample --framework net10.0
cd CSharpExample

CSharpExample.csproj settings used for these examples

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net10.0</TargetFramework>
    <LangVersion>12.0</LangVersion>
    <Nullable>enable</Nullable>
    <ImplicitUsings>disable</ImplicitUsings>
  </PropertyGroup>
</Project>

Build and run after saving one example in Program.cs

dotnet build
dotnet run --no-build

Continue learning

Change one input and predict the result before running it. Follow the related guides to connect this topic with the surrounding language features.

Syntax

await gate.WaitAsync(token);
try { /* protected work */ } finally { gate.Release(); }

Examples

Protect a small asynchronous section

Start two operations and allow only one inside at a time.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

using var gate = new SemaphoreSlim(1, 1);
await Task.WhenAll(Work("A"), Work("B"));
async Task Work(string name) {
    await gate.WaitAsync();
    try {
        Console.WriteLine(name + " entered");
        await Task.Yield();
        Console.WriteLine(name + " left");
    } finally { gate.Release(); }
}
  1. Work A synchronously acquires the initially available slot before its first scheduling yield.
  2. Work B cannot enter while A holds that slot; the finally returns it after A prints its exit.
  3. WhenAll waits for both operations before the semaphore is disposed. The initial setup determines this sample order; it does not establish a general fairness guarantee.
  4. Expected output: A entered A left B entered B left
  5. Pair each successful acquisition with one release.

Cancel a wait without over-releasing

Use an unavailable slot and an already-cancelled token.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

using var gate = new SemaphoreSlim(0, 1);
using var cancellation = new CancellationTokenSource();
cancellation.Cancel();
try {
    await gate.WaitAsync(cancellation.Token);
    try { Console.WriteLine("Entered"); }
    finally { gate.Release(); }
} catch (OperationCanceledException) { Console.WriteLine("Cancelled before entry"); }
Console.WriteLine(gate.CurrentCount);
  1. There is no available slot and the supplied token is cancelled.
  2. The wait fails before reaching the protected try/finally, so no Release runs.
  3. CurrentCount remains zero. Releasing in an outer unconditional finally would incorrectly create a slot.
  4. Expected output: Cancelled before entry 0
  5. Pair each successful acquisition with one release.

Best practices

  • Pair each successful acquisition with one release.
  • Keep cancellation and disposal ownership explicit.

Runtime & versions

.NET runtime. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

C# language reference

Specifications & further reading