Cancellationtoken In C#

In this guide, you will discover the process of incorporating the CancellationToken in C# along with an illustrative example.

What is the CancellationToken?

In C#, a robust feature for cooperative termination of asynchronous tasks is a CancellationToken. This functionality offers a straightforward method to halt operations that are no longer necessary or have exceeded their time limit. It allows a thread or Task to signal to another thread or Task that it intends to terminate its operation. The CancellationToken plays a crucial role in the Task Parallel Library (TPL) within the .NET framework, ensuring a uniform approach to terminating asynchronous tasks throughout different framework elements.

An efficient method to end asynchronous tasks is by utilizing CancellationToken. It enables cooperative cancellation of tasks and operations, allowing cancellation requests to be initiated from any section of the program.

Key Components:

Some primary elements of the CancellationToken in C# include:

  • CancellationToken: This symbolizes the token serving as a signal for cancellation.
  • Example
    
    CancellationTokenSource source = new CancellationTokenSource();
    
  1. CancellationTokenSource: Generating and managing the cancellation token offers a method to terminate operations.
  2. Example
    
    CancellationToken token = source.Token;
    

    Considerations:

  • Responsiveness: Asynchronous operations must continually check for cancellation requests to ensure a timely response to cancellations.
  • Thread Safety: CancellationToken and CancellationTokenSource are designed to be thread-safe, allowing safe use in multithreaded scenarios.
  • Features:

There are several features of the CancellationToken in C#. Some main key features are as follows:

  • Cooperative Cancellation: When a cancellation request is made, asynchronous processes should check the CancellationToken is IsCancellationRequested property and gracefully exit.
  • Cancellation Notification: By checking the token, any code that contains a reference to the CancellationToken may be informed when a cancellation request is made.
  • Exception Handling: When a cancellation is requested, operations may issue an OperationCanceledException, allowing for graceful cleanup.
  • Benefits:

There are several benefits of the CancellationToken in C#. Some main key benefits are as follows:

  • Graceful Shutdown: It allows applications to gracefully stop ongoing operations in response to user actions or system events.
  • Resource Management: It facilitates efficiently cleaning up resources associated with cancelled operations.
  • Concurrency Control: Promotes coordination between concurrent asynchronous tasks.

Task-oriented Approaches: In .NET, many asynchronous methods accept a CancellationToken as an optional parameter to facilitate cancellation.

For Example:

Example

async Task SomeAsyncOperation(CancellationToken cancellationToken)
{
await Task.Delay(1100, cancellationToken); 
//Example using Task.Delay supporting Cancellation
// Additional asynchronous operations
}

To request cancellation, employ the Cancel function from the corresponding CancellationTokenSource to notify a token of the cancellation.

Example

cancellationTokenSource.Cancel();

Verifying Cancellation: Utilize the IsCancellationRequested property within the asynchronous function to check if a cancellation has been requested.

Example

while (!cancellationToken.IsCancellationRequested)
{
    //Write Code here
}
  1. To handle OperationCanceledException, encapsulate the potentially cancelable code within a try-catch block to avoid propagating the OperationCanceledException.
  2. Example
    
    try
    {
        //Code that may throw an exception called "OperationCanceledException
    "
    }
    catch (OperationCanceledException)
    {
        // Handle cancellation here
    }
    

    Example:

Let's consider a scenario to demonstrate the usage of the CancellationToken in C#.

Example

using System;
using System.Threading;
using System.Threading.Tasks;
class Demo
{
    static async Task Main(string[] args)
    {
        // Create a CancellationTokenSource
        CancellationTokenSource source = new CancellationTokenSource();
        // The CancellationToken can be obtained via the CancellationTokenSource.
        CancellationToken token = source.Token;
        // Start an application that performs an asynchronous operation.
        Task t = Task.Run(async () =>
        {
            try
            {
                while (!token.IsCancellationRequested)
                {
                    Console.WriteLine("The Task is running successfully...");
                    await Task.Delay(1100); 
                    // Simulated an asynchronous operation
                }
            }
            catch (OperationCanceledException)
            {
                Console.WriteLine("The Task was canceled.");
            }
        });
        // Waiting for user input to cancel the Task
        Console.WriteLine("Press Enter to cancel the task...");
        Console.ReadLine();
        // Cancel the Task by cancelling the CancellationTokenSource
        source.Cancel();
        // Wait for the Task to complete
        try
        {
            await t;
        }
        catch (OperationCanceledException)
        {
            Console.WriteLine("The Task was canceled before completion.");
        }
        Console.WriteLine("Press any key to exit...");
        Console.ReadKey();
    }
}

Output:

Output

Press Enter to cancel the Task...
The Task is running successfully...
The Task is running successfully...
The Task is running successfully...
The Task is running successfully...
The Task is running successfully...
Press any key to exit...

Explanation:

This C# example illustrates the utilization of a CancellationToken for gracefully terminating an asynchronous operation. To commence, you need to instantiate a CancellationTokenSource and acquire a corresponding CancellationToken from it. Subsequently, an asynchronous task is initiated to monitor cancellation requests at regular intervals. Triggering Cancel on the CancellationTokenSource halts the Task when prompted by the user. Finally, it awaits the Task's conclusion, managing any OperationCanceledException thrown if the task was terminated prematurely.

Usage Scenarios

CancellationToken is commonly applied in scenarios where external factors like user interactions, timeouts, or system shutdowns necessitate canceling asynchronous tasks. This functionality helps avoid resource wastage and guarantees that applications can gracefully end extended operations.

Conclusion:

In summary, the CancellationToken in C# offers a robust and standardized feature for cooperatively terminating asynchronous tasks. It guarantees efficient resource management and speediness, enabling applications to gracefully manage cancellation events through token distribution and checking for cancellation requests.

Input Required

This code uses input(). Please provide values below: