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 = ...

Get Visual Basic® 2010 Unleashed 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.