Select Page

An asynchronous failure test must observe the returned task. A call that returns without throwing can still fail later, after an await. Cancellation needs a separate check: requesting it does not prove that the operation accepted it.

This tutorial tests both outcomes with a controllable input task. You choose exactly when the operation can continue, then assert its exception, completion state, and cleanup. Two deliberately broken variants show that the checks can detect a swallowed failure and ignored cancellation.

Verified 8 November 2026 using the pinned .NET 10 SDK container, targeting net10.0 with its default C# language version. The complete program compiled with zero warnings and errors, ran without network access, and produced the exact output below. It uses only the base class library.

Choose the contract and the suspension point

The example worker doubles a supplied integer. Negative input must fail with InvalidOperationException. Once input arrives, a requested cancellation must produce OperationCanceledException carrying the caller’s token. Every terminal path must increment the cleanup counter exactly once.

These are application rules for this example. In particular, the worker checks cancellation after receiving input. Even an already canceled token leaves it waiting until the input arrives. This deliberate policy lets the tests distinguish a cancellation request from its observation; it is not a design for promptly cancelable I/O.

A TaskCompletionSource<T> lets the test own completion of the input task. Before SetResult, the worker must be incomplete. After release, the test awaits its terminal outcome. No sleep duration is used to guess whether execution reached the suspension point.

Checks made with a fresh worker and input gate
Case Controlled action Required outcome
Success Release input 21 Result 42, successful task, cleanup once
Failure Release input -1 Exact exception type and reason, faulted task, cleanup once
Cancel after start Cancel while input is pending, then release 21 Cancellation exception with matching token, canceled task, cleanup once
Cancel before start Cancel first, start worker, then release 21 Same cancellation contract at the later checkpoint

Compile and run the complete checks

With the .NET 10 SDK installed, create a console project:

dotnet new console --framework net10.0 --name AsyncChecks
cd AsyncChecks

Replace all of Program.cs with this listing, then run dotnet run. This is a console assertion harness; it has no test discovery or dotnet test integration. An unexpected check failure terminates the program.

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

class Program
{
    sealed class CheckFailed(string message) : Exception(message) { }

    sealed class Worker
    {
        public int CleanupCount { get; private set; }

        public async Task<int> DoubleAsync(Task<int> input, CancellationToken token,
            bool swallowFailure = false, bool ignoreCancellation = false)
        {
            try
            {
                int value = await input;
                if (!ignoreCancellation) token.ThrowIfCancellationRequested();
                if (value < 0)
                {
                    if (swallowFailure) return 0; // Deliberate defect for a negative control.
                    throw new InvalidOperationException("Negative input.");
                }
                return checked(value * 2);
            }
            finally
            {
                CleanupCount++;
            }
        }
    }

    static void Require(bool condition, string message)
    {
        if (!condition) throw new CheckFailed(message);
    }

    static async Task<T> ExpectAsync<T>(Task task) where T : Exception
    {
        try { await task; }
        catch (T error) { return error; }
        throw new CheckFailed($"Expected {typeof(T).Name}.");
    }

    static TaskCompletionSource<int> Gate() =>
        new(TaskCreationOptions.RunContinuationsAsynchronously);

    static async Task SuccessCase()
    {
        var gate = Gate();
        var worker = new Worker();
        Task<int> task = worker.DoubleAsync(gate.Task, CancellationToken.None);
        Require(!task.IsCompleted, "Operation must be waiting at the gate.");
        gate.SetResult(21);
        Require(await task == 42, "Wrong result.");
        Require(task.IsCompletedSuccessfully, "Expected successful completion.");
        Require(worker.CleanupCount == 1, "Success cleanup missing.");
    }

    static async Task FaultCase(bool swallowFailure = false)
    {
        var gate = Gate();
        var worker = new Worker();
        Task<int> task = worker.DoubleAsync(gate.Task, CancellationToken.None,
            swallowFailure: swallowFailure);
        Require(!task.IsCompleted, "Failure must occur after suspension.");
        gate.SetResult(-1);
        InvalidOperationException error = await ExpectAsync<InvalidOperationException>(task);
        Require(error.GetType() == typeof(InvalidOperationException), "Wrong exception type.");
        Require(error.Message == "Negative input.", "Wrong failure reason.");
        Require(task.IsFaulted && !task.IsCanceled, "Expected faulted task.");
        Require(worker.CleanupCount == 1, "Fault cleanup missing.");
    }

    static async Task CancellationCase(bool cancelBeforeStart,
        bool ignoreCancellation = false)
    {
        using var stop = new CancellationTokenSource();
        if (cancelBeforeStart) stop.Cancel();
        var gate = Gate();
        var worker = new Worker();
        Task<int> task = worker.DoubleAsync(gate.Task, stop.Token,
            ignoreCancellation: ignoreCancellation);
        Require(!task.IsCompleted, "Operation must be waiting at the gate.");
        if (!cancelBeforeStart) stop.Cancel();
        Require(stop.IsCancellationRequested, "Cancellation was not requested.");
        Require(!task.IsCompleted, "This input gate does not observe cancellation.");
        gate.SetResult(21);
        OperationCanceledException error = await ExpectAsync<OperationCanceledException>(task);
        Require(error.CancellationToken == stop.Token, "Wrong cancellation token.");
        Require(task.IsCanceled && !task.IsFaulted, "Expected canceled task.");
        Require(worker.CleanupCount == 1, "Cancellation cleanup missing.");
    }

    static async Task Main()
    {
        await SuccessCase();
        Console.WriteLine("PASS: result 42 and success cleanup");
        await FaultCase();
        Console.WriteLine("PASS: awaited failure, faulted task and cleanup");
        await CancellationCase(cancelBeforeStart: false);
        Console.WriteLine("PASS: cancellation after start, token and cleanup");
        await CancellationCase(cancelBeforeStart: true);
        Console.WriteLine("PASS: cancellation before start, token and cleanup");
        CheckFailed fault = await ExpectAsync<CheckFailed>(FaultCase(swallowFailure: true));
        Require(fault.Message == "Expected InvalidOperationException.", "Wrong negative control failure.");
        Console.WriteLine("REJECTED: swallowed failure");
        CheckFailed cancellation = await ExpectAsync<CheckFailed>(
            CancellationCase(cancelBeforeStart: false, ignoreCancellation: true));
        Require(cancellation.Message == "Expected OperationCanceledException.", "Wrong negative control failure.");
        Console.WriteLine("REJECTED: ignored cancellation");
    }
}

Expected output:

PASS: result 42 and success cleanup
PASS: awaited failure, faulted task and cleanup
PASS: cancellation after start, token and cleanup
PASS: cancellation before start, token and cleanup
REJECTED: swallowed failure
REJECTED: ignored cancellation

Assert the awaited failure, not just the call

FaultCase starts the worker while its input is incomplete. Checking for a synchronous exception around that call would miss the later negative-input failure. ExpectAsync instead awaits the actual worker task. Microsoft explains that callers observe asynchronous exceptions by awaiting the task.

The helper catches the requested exception family and returns the exception for further assertions. Its “expected exception” failure is thrown outside that catch, so it cannot satisfy itself. The fault test additionally requires the exact runtime type and the example’s message. That message is our contract, not a localized framework message to rely on.

The swallowFailure flag deliberately replaces the negative-input exception with a successful zero result. The same FaultCase must reject it for the specific missing-exception reason. Only that expected assertion failure is accepted by Main; the broken behavior does not count as a passing worker implementation.

Distinguish requested cancellation from a canceled task

CancellationCase confirms that the source was canceled while the worker remained pending at the input gate. It then releases the gate and awaits the worker. Microsoft’s cancellation guidance describes cancellation as cooperative and uses ThrowIfCancellationRequested to signal it.

The check accepts OperationCanceledException and derived types, verifies its token, and requires IsCanceled with IsFaulted false. Those assertions identify the outcome of this worker. Merely inspecting IsCancellationRequested would also pass the deliberately broken ignoreCancellation variant, which returns 42. The awaited exception check rejects that variant.

Each cancellation case disposes its own source with using. Every case creates a fresh worker and gate, and awaits the worker after releasing it. The cleanup counter establishes that this example’s finally block ran once. It does not establish that a real socket, transaction, or file was released.

Know what these checks leave open

The tests cover the selected orderings and one suspension point. They do not prove prompt cancellation, every scheduling race, thread safety, network behavior, or cancellation propagation through a real dependency. The input gate has no cancellation support. For an operation that must stop while awaiting I/O, test that dependency’s cancellation contract and verify its observable cleanup separately.

When transferring these checks into your existing test framework, keep the test method asynchronous and await the returned assertion operation. Preserve the controlled release and the defect checks. Remove the two mutation flags from production code; they exist here only to demonstrate which mistakes the assertions catch.

Continue with CancellationToken propagation across application layers for token forwarding, or async streams and cancellation for iterator-specific behavior. If exception handling is unfamiliar, start with C# exception handling.

Share This