5 ways Cancel doesn't actually cancel in C#
A user clicks Export , changes their mind, and clicks Cancel . The spinner goes away. On the server, the export keeps running to the end and saves a file nobody wants. CancellationToken only works if every piece of code along the way cooperates. Here are five ways it quietly doesn't. Each demo logs a timestamp, the "Cancel" click is simulated, and every output is copied from actually running it…
Task cancellation in C# can be tricky, with several pitfalls that can lead to unexpected behavior. Here are five common ways that using CancellationToken doesn't actually cancel operations in C#.
First, passing the cancellation token to Task.Run and nowhere else can cause problems. In the demo, clicking Cancel stops the task from starting, but the actual work continues to run and completes. To properly cancel, the cancellation token must be passed into the work and checked within it.
Second, if a cancellation token is taken and not passed on, operations can still run to completion even when the user clicks Cancel. The demo shows this when the LoadPricesAsync method accepts a cancellation token but doesn't forward it to the Api.FetchAsync method. When the token is forwarded, the cancellation works as expected.
Third, stopping quietly instead of loudly can result in partial work being saved as if it were complete. In the ExportAsync method, the code checks for cancellation but uses break to exit the loop. This drops to the code after the loop, allowing the partial report to be saved. To properly cancel, the code should throw an exception, like TaskCanceledException, which interrupts the wait operation.
Fourth, catching the wrong exception type can lead to incorrect handling of cancellations. In the SearchAsync method, the catch block only catches TaskCanceledException. This means other cancellation-related exceptions are not handled properly. To avoid this issue, catch more general exceptions or use a more specific catch block that handles all cancellation-related exceptions.
Lastly, it's important to remember that CancellationToken only works if all pieces of code along the way cooperate. If any part of the operation doesn't check the token for cancellation, the cancellation may not take effect as intended. Ensuring that all code paths consider the cancellation token is crucial for reliable task cancellation in C#.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.