bhylu.com

Advertisements

C# Cancellation

Pass a token into an operation and distinguish a cancelled request from an ordinary failure.

How it works

Cancellation asks an operation to stop; it does not forcibly terminate arbitrary work. A CancellationTokenSource owns a request mechanism and produces tokens passed to cooperating APIs. Check cancellation before expensive steps and pass the token through child calls. OperationCanceledException is the normal signal for this pattern, but a boundary should confirm that the cancellation belongs to the request it is handling. Resource cleanup still needs using or finally after a cancellation path.

Run it locally

Use the .NET 10 SDK with C# 14 in a separate console lab. Create an empty project once with dotnet new console --framework net10.0, then replace Program.cs with this complete source and add any supporting files shown. Keep only one lesson entry point in the project. C# does not currently run in Bhylu’s browser playground. Apache, PHP and MySQL are not needed.

dotnet build -p:LangVersion=14.0 -p:Nullable=enable -p:TreatWarningsAsErrors=true
dotnet run --no-build

Use the SDK’s project workflow; the review compiles against its matching reference assemblies and executes the results without external NuGet packages. File-writing examples belong in a private empty lab directory.

Download the complete C# source as Program.cs.

Example

C# 14 · Program.cs

using System;
using System.Threading;
using System.Threading.Tasks;

internal static class Program
{
    private static async System.Threading.Tasks.Task Main(string[] args)
    {
        using var source = new CancellationTokenSource();
        source.Cancel();
        try { await Task.Delay(10, source.Token); }
        catch (OperationCanceledException) when (source.IsCancellationRequested)
        {
            Console.WriteLine("Request cancelled");
        }
    }
}

Expected result

Request cancelled

The source is cancelled before the delay begins, making the fixture deterministic without waiting for a real timeout. Production operations should accept a caller token rather than silently create an unrelated token at every layer. Cancellation can happen after external side effects, so it does not mean a booking was automatically undone or never committed.

Consult Microsoft’s C# documentation for language and library contracts, including target-framework and version requirements.