Javatpoint Logo
Javatpoint Logo

CancellationToken in C#

In this article, you will learn how to implement the CancellationToken in C# with its example.

What is the CancellationToken?

In C#, a powerful mechanism for cooperative cancellation of asynchronous operations is a CancellationToken. It provides an easy approach to cancelling operations that are no longer needed or have timed out by enabling a thread or Task to indicate to another thread or Task that it wishes to cancel its operation. CancellationToken is an essential component of the Task Parallel Library (TPL) in .NET, providing a standardised way of cancelling asynchronous operations across various framework components.

An effective way to terminate asynchronous actions is through the use of CancellationToken. Cooperative cancellation of tasks and operations is possible, and cancellation requests can be started from any part of the programme.

Key Components:

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

1. CancellationToken: It represents the token that can be used as a cancellation signal.

2. CancellationTokenSource: Creating and handling the cancellation token provides a way to cancel operations.

Considerations:

  1. Responsiveness: Asynchronous operations must continually check for cancellation requests to ensure a timely response to cancellations.
  2. 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:

  1. Cooperative Cancellation: When a cancellation request is made, asynchronous processes should check the CancellationToken is IsCancellationRequested property and gracefully exit.
  2. Cancellation Notification: By checking the token, any code that contains a reference to the CancellationToken may be informed when a cancellation request is made.
  3. 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:

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

Passing CancellationToken to Operations

1. Task-based Methods: A CancellationToken is an optional parameter accepted by most asynchronous methods in .NET to allow cancellation.

For Example:

2. Cancellation Request: Use the Cancel() methodof the related CancellationTokenSource to signal cancellation to a token.

Handling Cancellation:

1. Checking for Cancellation: Use the IsCancellationRequested property in the asynchronous method to determine whether cancellation is being requested.

2. Catching OperationCanceledException: Wrap code that could cause cancellation in a try-catch block to prevent it from throwing an OperationCanceledException.

Example:

Let us take an example to illustrate the CancellationToken in C#.

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# code demonstrates how to use a CancellationToken to gently cancel an asynchronous activity. In order to start, a CancellationTokenSource must be created and a CancellationToken must be obtained from it. Next, it launches an asynchronous task to check for cancellation requests while operating periodically. Calling Cancel() on the CancellationTokenSource cancels the Task upon user input. Finally, it waits for the Task to complete, handling the OperationCanceledException if it was cancelled before completion.

Usage Scenarios

CancellationToken is frequently used when external events, such as user input, timeouts, or application shutdown, require the cancellation of asynchronous operations. To prevent resource leaks and ensure responsiveness, it enables applications to terminate long processes gracefully.

Conclusion:

In conclusion, C#'s CancellationToken provides a powerful and standardized mechanism for cooperatively cancelling asynchronous operations. It ensures resource effectiveness and rapidity while allowing applications to handle cancellation events gracefully by distributing tokens and checking for cancellation requests.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA