DEV Community

Cover image for C# - Asynchronous Programming with Cancellation Tokens
Keyur Ramoliya
Keyur Ramoliya

Posted on

C# - Asynchronous Programming with Cancellation Tokens

Cancellation tokens provide a way to gracefully cancel asynchronous operations. They are useful when you want to allow users to cancel long-running tasks or when you need to terminate asynchronous operations in response to certain conditions.

Here's an example that demonstrates how to use cancellation tokens:

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

public class Program
{
    public static async Task Main()
    {
        using var cancellationTokenSource = new CancellationTokenSource();
        CancellationToken cancellationToken = cancellationTokenSource.Token;

        // Start an asynchronous operation
        var task = PerformAsyncOperation(cancellationToken);

        // Simulate a cancellation request after 2 seconds
        await Task.Delay(2000);
        cancellationTokenSource.Cancel();

        try
        {
            // Await the task and handle potential exceptions
            await task;
            Console.WriteLine("Operation completed successfully.");
        }
        catch (OperationCanceledException)
        {
            Console.WriteLine("Operation was canceled.");
        }
    }

    public static async Task PerformAsyncOperation(CancellationToken cancellationToken)
    {
        try
        {
            while (true)
            {
                // Check for cancellation request before each step
                cancellationToken.ThrowIfCancellationRequested();

                // Simulate a step in the operation
                await Task.Delay(1000);
                Console.WriteLine("Step completed.");
            }
        }
        catch (OperationCanceledException)
        {
            Console.WriteLine("Operation was canceled.");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example:

  • We create a CancellationTokenSource to generate cancellation tokens.
  • We start an asynchronous operation using PerformAsyncOperation and pass in the cancellation token.
  • After 2 seconds, we cancel the operation using cancellationTokenSource.Cancel().
  • We catch and handle the OperationCanceledException that is thrown when the operation is canceled.

Cancellation tokens allow you to implement cooperative cancellation in your asynchronous code, ensuring that operations can be safely canceled without causing resource leaks or unexpected behavior. They are especially valuable when working with long-running tasks or tasks that depend on external conditions for termination.

Top comments (0)