CancellationTokenSource Class

Namespace: System.Threading

Represents the mechanism that ITask implementations use to notify operations that they should be canceled.

Syntax


public class CancellationTokenSource

Remarks

The CancellationTokenSource class creates and manages a CancellationToken. When the CancellationTokenSource is disposed, its associated CancellationToken is signaled, and any operations that are listening for cancellation will be notified.

You can use CancellationTokenSource to cancel asynchronous operations, such as those returned by the Task Parallel Library (TPL). This allows you to gracefully stop operations that are no longer needed, freeing up resources and improving application responsiveness.

Constructors

CancellationTokenSource()

Initializes a new instance of the CancellationTokenSource class.

CancellationTokenSource(int millisecondsDelay)

Initializes a new instance of the CancellationTokenSource class with a specified delay in milliseconds.

Properties

IsCancellationRequested

Gets a value that indicates whether cancellation has been requested.


public bool IsCancellationRequested { get; }

Token

Gets the CancellationToken associated with this CancellationTokenSource.


public CancellationToken Token { get; }

Methods

Cancel()

Notifies the listeners that the operating environment has canceled the request.


public void Cancel();

CancelAfter(int millisecondsDelay)

Sets the timer for the current CancellationTokenSource instance to cancel after the specified delay.


public void CancelAfter(int millisecondsDelay);

Dispose()

Releases all resources used by the current instance of the CancellationTokenSource class.


public void Dispose();

Example

Using CancellationTokenSource to cancel a long-running operation:


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

public class Example
{
    public static async Task Main(string[] args)
    {
        // Create a CancellationTokenSource
        using (var cts = new CancellationTokenSource())
        {
            Console.WriteLine("Starting a long-running operation...");

            // Start a task that can be cancelled
            var longRunningTask = Task.Run(() => DoWork(cts.Token));

            // Wait for a few seconds, then cancel the operation
            await Task.Delay(3000);
            Console.WriteLine("Cancelling the operation...");
            cts.Cancel();

            try
            {
                await longRunningTask;
                Console.WriteLine("Operation completed successfully (unexpected).");
            }
            catch (OperationCanceledException)
            {
                Console.WriteLine("Operation was successfully cancelled.");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"An unexpected error occurred: {ex.Message}");
            }
        }
    }

    public static void DoWork(CancellationToken cancellationToken)
    {
        for (int i = 0; i < 10; i++)
        {
            // Check if cancellation has been requested
            cancellationToken.ThrowIfCancellationRequested();

            Console.WriteLine($"Working... Step {i + 1}");
            Thread.Sleep(500); // Simulate work
        }
        Console.WriteLine("Work completed without cancellation.");
    }
}