The System.Threading.Tasks.Task and System.Threading.Tasks.Task(Of TResult) classes support cancellation through the use of cancellation tokens in the .NET Framework. For more information, see Cancellation in Managed Threads. In the Task classes, cancellation involves cooperation between the user delegate, which represents a cancelable operation and the code that requested the cancellation. A successful cancellation involves the requesting code calling the CancellationTokenSource.Cancel method, and the user delegate terminating the operation in a timely manner. You can terminate the operation by using one of these options:
By simply returning from the delegate. In many scenarios this is sufficient; however, a task instance that is canceled in this way transitions to the TaskStatus.RanToCompletion state, not to the TaskStatus.Canceled state.
By throwing a OperationCanceledException and passing it the token on which cancellation was requested. The preferred way to do this is to use the ThrowIfCancellationRequested method. A task that is canceled in this way transitions to the Canceled state, which the calling code can use to verify that the task responded to its cancellation request.
The following example shows the basic pattern for task cancellation that throws the exception. Note that the token is passed to the user delegate and to the task instance itself.
Imports System.Threading Imports System.Threading.Tasks Module Test Sub Main() Dim tokenSource2 As New CancellationTokenSource() Dim ct As CancellationToken = tokenSource2.Token Dim t2 = Task.Factory.StartNew(Sub() ' Were we already canceled? ct.ThrowIfCancellationRequested() Dim moreToDo As Boolean = True While moreToDo = True ' Poll on this property if you have to do ' other cleanup before throwing. If ct.IsCancellationRequested Then ' Clean up here, then... ct.ThrowIfCancellationRequested() End If End While End Sub _ , tokenSource2.Token) ' Pass same token to StartNew. ' Cancel the task. tokenSource2.Cancel() ' Just continue on this thread, or Wait/WaitAll with try-catch: Try t2.Wait() Catch e As AggregateException For Each item In e.InnerExceptions Console.WriteLine(e.Message & " " & item.Message) Next Finally tokenSource2.Dispose() End Try Console.ReadKey() End Sub End Module
For a more complete example, see How to: Cancel a Task and Its Children.
When a task instance observes an OperationCanceledException thrown by user code, it compares the exception's token to its associated token (the one that was passed to the API that created the Task). If they are the same and the token's IsCancellationRequested property returns true, the task interprets this as acknowledging cancellation and transitions to the Canceled state. If you do not use a Wait or WaitAll method to wait for the task, then the task just sets its status to Canceled.
If you are waiting on a Task that transitions to the Canceled state, a TaskCanceledException.Task (wrapped in an AggregateException) is manufactured and thrown. Note that this exception indicates successful cancellation instead of a faulty situation. Therefore, the Task's Exception property returns null.
If the token's IsCancellationRequested property returns false or if the exception's token does not match the Task's token, the OperationCanceledException is treated like a normal exception, causing the Task to transition to the Faulted state. Also note that the presence of other exceptions will also cause the Task to transition to the Faulted state. You can get the status of the completed task in the Status property.
It is possible that a task may continue to process some items after cancellation is requested.