Determining If a Task Was Cancelled

You can determine if a Task has been cancelled by checking the IsCancelled property, which will return true if the Task was cancelled. Listing 2-12 demonstrates the use of this property.

Listing2-12. Using the Task.isCancelled Property using System;

using System.Threading;

using System.Threading.Tasks;

namespace Listing_12 {

class Listing_12 {

static void Main(string[] args) {

// create the cancellation token source

CancellationTokenSource tokenSource1 = new CancellationTokenSource(); // create the cancellation token CancellationToken token1 = tokenSource1.Token;

// create the first task, which we will let run fully Task task1 = new Task(() => {

token1.ThrowIfCancellationRequested(); Console.WriteLine("Task 1 - Int value {0}", i);

// create the second cancellation token source

CancellationTokenSource tokenSource2 = new CancellationTokenSource(); // create the cancellation token CancellationToken token2 = tokenSource2.Token;

// create the second task, which we will cancel Task task2 = new Task(() => {

for (int i = 0; i < int.MaxValue; i++) { token2.ThrowIfCancellationRequested(); Console.WriteLine("Task 2 - Int value {0}", i);

// start all of the tasks taskl.Start();

task2.Start();

// cancel the second token source tokenSource2.Cancel();

// write out the cancellation detail of each task Console.WriteLine("Task 1 cancelled? {0}", taskl.IsCanceled); Console.WriteLine("Task 2 cancelled? {o}", task2.IsCanceled);

// wait for input before exiting

Console.WriteLine("Main method complete. Press enter to finish."); Console.ReadLine();

The code in Listing 2-12 creates two Tasks, each of which is constructed using a CancellationToken from a different CancellationTokenSource. The CancellationTokenSource for the second Task is cancelled, but the first Task is allowed to complete normally. The values of the IsCanceled property are printed out for each of the tasks. Running the code produces results similar to the following:

Task 1 cancelled? False Task 2 cancelled? True Task 1 - Int value 0

Task 1 - Int value 9

Main method complete. Press enter to finish.

0 0

Post a comment