Programming Languages

CancellationToken in C#: Requesting a Stop Is Not Killing a Task

SoftwareJobs.io editorial24 November 20262 min read

An async operation may no longer be needed because a user leaves a screen or a time limit is reached. In C#, cancellation is a request that cooperating code observes. It is not a command that forcibly kills any task.

Follow the token

A CancellationTokenSource can request cancellation. Its token is passed to work that supports cancellation. Microsoft’s async cancellation example passes a token into HTTP operations and handles an OperationCanceledException.

static async Task<string> LoadAsync(
    HttpClient client, string url, CancellationToken token)
{
    return await client.GetStringAsync(url, token);
}

This is a method sketch, not a complete application. The caller must provide the client, URL and token and decide how to handle completion, errors and cancellation. Passing a token only helps where the called operation observes it.

Use a small practice scenario

Imagine a search screen that no longer needs an old result. Draw the path from the caller through your service to the operation doing the work. Mark where the token is passed. Then ask what happens if the operation completes just before the cancellation request arrives.

Checks worth discussing

  • The normal request completes.
  • Cancellation requested before starting is handled.
  • Cancellation during work is handled.
  • An ordinary failure is not incorrectly described as cancellation.

For a .NET interview in Malta, explain who owns the request to stop and how the application responds. The important point is useful control over work, not simply adding a token parameter to a method that never uses it.

Sources and further reading

Browse current technology jobs in Malta →

PUT YOUR IDEAS INTO ACTION

What’s your next move?

Explore software, cloud and data roles that fit your skills and ambitions.

Explore opportunities
KEEP EXPLORING

More ideas for your next chapter