Task cancellation

A task represents a common asynchronous operation. This means that we don't know when it completes. Sometimes, it is clear that we do not need this task anymore. For example, if the operation takes too long to complete, or the user clicks on the Cancel button. In this case, we need to stop the task.

One of the lower-level ways to stop a thread is by calling its Abort method. Before going on, I would like to emphasize the importance of not using this.

Note

Never ever use Thread.Abort!

Thread.Abort raises a very special exception called ThreadAbortException on a thread that is being aborted. This exception can happen at more or less any point in your program and cannot be stopped by the usual exception handling. We can write a code ...

Get Mastering C# Concurrency now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.