05 November 2026

C# async and await with CancellationToken: A Runnable Console Example

  Asp.Net CS By Example       05 November 2026

Asynchronous code becomes easier to understand when the example has no database, API key or network dependency. This small console application performs five simulated steps. Run it normally to request cancellation, or pass --complete to let all five steps finish.

What the keywords mean

A method returning Task represents an operation that may still be running. Task<int> also provides an integer result. The async modifier permits await in the method body. Await lets execution continue after the awaited operation finishes, without blocking the current thread while waiting. It does not automatically start an additional thread or make a CPU-heavy calculation faster.

1. Create a console application

dotnet new console -n AsyncDemo
cd AsyncDemo

Use a modern .NET SDK. This example uses top-level statements, supported by current console project templates. It is a console example, not code to paste directly into a Web Forms page event.

2. Replace Program.cs

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

using var cancellation = new CancellationTokenSource();
if (!args.Contains("--complete"))
    cancellation.CancelAfter(TimeSpan.FromMilliseconds(1100));

try
{
    int completed = await ProcessStepsAsync(cancellation.Token);
    Console.WriteLine($"Completed {completed} steps.");
}
catch (OperationCanceledException) when (cancellation.IsCancellationRequested)
{
    Console.WriteLine("Work was canceled.");
}

static async Task<int> ProcessStepsAsync(CancellationToken token)
{
    for (int step = 1; step <= 5; step++)
    {
        await Task.Delay(400, token);
        Console.WriteLine($"Finished step {step}");
    }
    return 5;
}

3. Try cancellation

dotnet run

Each step waits approximately 400 milliseconds. CancelAfter requests cancellation after about 1.1 seconds. A typical run produces:

Finished step 1
Finished step 2
Work was canceled.

Exact scheduling can vary. The important result is that the awaited delay observes the token and the cancellation handler runs. Cancellation is cooperative: code must pass the token to a supporting operation or check it explicitly.

4. Try successful completion

dotnet run -- --complete

The double dash separates arguments for dotnet run from arguments passed to the program. This option skips the scheduled cancellation, so the expected final output is:

Finished step 1
Finished step 2
Finished step 3
Finished step 4
Finished step 5
Completed 5 steps.

Follow the flow

  1. The caller creates and owns the CancellationTokenSource.
  2. The worker receives only its token, so it can observe cancellation without owning the source.
  3. Task.Delay receives that token on every iteration.
  4. The caller awaits the worker and handles cancellation separately from successful completion.
  5. The using declaration disposes the source when the program finishes.

Common mistakes

  • Forgetting to await a returned task can let a console program exit before its work finishes.
  • Thread.Sleep blocks a thread. Use a cancellable Task.Delay for a simulated asynchronous wait.
  • Avoid .Result and .Wait() when an await-based call chain is available.
  • Prefer Task-returning methods for ordinary asynchronous work; async void is generally reserved for event handlers.
  • Do not catch every exception and call it cancellation. This handler filters for the cancellation source used by this example.

Where to go next

Replace the artificial delay with a real asynchronous file, HTTP or database operation that accepts a token. Cancellation does not undo work already committed to an external system, so define that separately.

This exact example was compiled with .NET SDK 9.0.306 and run in both cancellation and successful-completion modes.

Related basics

C# Variables and try-catch-block-Exceptions-Handling.

References

logoblog

Thanks for reading C# async and await with CancellationToken: A Runnable Console Example

Previous
« Prev Post

No comments:

Post a Comment

Please do not enter any spam link in the comment box.