Graceful Exits: Using Cancellation Tokens in C#

IT Sharky
3 min readMar 1, 2024

In the fast-paced world of software development, sometimes we need to hit the brakes. Long-running operations might become outdated, user interactions might change course, or external factors might necessitate a quick shutdown. This is where cancellation tokens come in, providing a mechanism for cooperative cancellation of tasks in C#.

What are Cancellation Tokens?

Imagine a waiter taking your order at a restaurant. You can politely tell them to cancel your order before it’s prepared, allowing them to adjust their workflow accordingly. Cancellation tokens work in a similar way for long-running tasks in your code. They act as a signal to the executing code, politely requesting it to stop what it’s doing and clean up any resources it might be holding.

How to Use Cancellation Tokens

Cancellation tokens are implemented through the CancellationTokenSource and CancellationToken classes in the System.Threading namespace. Here's a breakdown of their roles:

  • CancellationTokenSource: This class acts as a factory that creates CancellationToken instances and also holds the authority to cancel them.
  • CancellationToken: This is a lightweight struct passed around to different parts of your code. It cannot initiate…

--

--