Cancelling Tasks
There are situations in which you want to cancel task execution. To programmatically cancel a task, you need to enable tasks for cancellation, which requires some lines of code. You need an instance of the System.Threading.CancellationTokenSource class; this instance tells to a System.Threading.CancellationToken that it should be canceled. The CancellationToken class provides notifications for cancellation. The following lines declare both objects:
Dim tokenSource As New CancellationTokenSource() Dim token As CancellationToken = tokenSource.Token
Then you can start a new task using an overload of the TaskFactory.StartNew method that takes the cancellation token as an argument. The following line accomplishes this:
Dim aTask = ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access