Site icon

Understanding Task Cancellation in C#

In C# asynchronous programming, Tasks allow you to perform operations without blocking the main thread, which improves performance and responsiveness of the applications. However, sometimes you may need to cancel an ongoing task due to some programming need, this is where Task Cancellation come into play.

The Task Parallel Library (TPL) provides a reliable and robust mechanism to cancel tasks gracefully in C#.

Key Components of Task Cancellation in C#

Task cancellation involves several key components in C#:

What is CancellationTokenSource?

CancellationTokenSource (known as CTS) generates CancellationToken objects and signals the token when it is cancelled.

Essentially, the CancellationTokenSource acts as a controller, when you want to cancel a task, you call the Cancel method on the CancellationTokenSource, which then signals the CancellationToken.

What is a Cancellation Token?

A CancellationToken in C# is part of System.Threading namespace enables polling for a cancellation request, this token works in coordination with CancellationTokenSource.

How to Cancel Tasks in C# using Cancellation Token?

Let’s walk through an example to understand step by step process of cancelling a task using cancellation tokens in C#.

In the above example.

When we run the above example following output generated.

Task_Cancellation_OutPut_1.0

The program starts printing the Even Numbers in the console output and once the Cancellation initiated then the Task just exited gracefully.

Conclusion

Cancellation tokens are a powerful feature in C# that allow developers to manage tasks more effectively. It improves the responsiveness and resource management of your applications, especially in scenarios that involves long-running operations.

Thanks for visiting 🙂 Please have a look at some of my other blogs on similar topic and provide your valuable feedback or comments.

Tasks in C#

Tasks in C# Extended

Async and await in C#

Exit mobile version