Task Cancellation: Parallel Programming – III


This is my third article on Parallel programming. Last two articles are on Data Parallelism and Task Parallelism.

You can read my previous article here:

Begin with Parallel programming in Dotnet 4.0

Task Parallelism: Parallel programming – II

Today I am writing about how to cancel parallel tasks in cooperative manner i.e. dotnet framework doesn’t force your tasks to finish the task.

Task execution can be cancelled through use of cancellation Token which is new in DotNet Framework4.0. Task class supports Cancellation with the integration with System.Threading.CancellationTokenSource class and the System.Threading.CancellationToken class. Many of the constructors in the System.Threading.Tasks.Task class take a CancellationToken as an input parameter. Many of the StartNew overloads also take a CancellationToken.

CancellationTokenSource contains CancellationToken and Cancel method  through which cancellation request can be raised. I’ll cover following type of cancellation here:

  1. Cancelling a task.
  2. Cancelling Many Tasks
  3. Monitor tokens

Cancelling Task

Following steps will describe how to cancel a task:

    1. First create instance of CancellationTokenSource class
    2. Create instance of CancellationToken by setting Token property of CancellationTokenSource class.
    3. Start task by TaskFactory.StartNew method or Task.Start().
    4. Check for token.IsCancellationRequested property or token.ThrowIfCancellationRequested() for Cancellation Request.
    5. Execute Cancel method of CancellationTokenSource class to send cancellation request to Task.

SourceCode

            CancellationTokenSource tokenSource = new CancellationTokenSource();
            CancellationToken token = tokenSource.Token;

            int i = 0;
            Console.WriteLine("Calling from Main Thread {0}", System.Threading.Thread.CurrentThread.ManagedThreadId);
            var task = Task.Factory.StartNew(() =>
            {
		while (true)
                {
                    if (token.IsCancellationRequested)
                    {
                        Console.WriteLine("Task cancel detected");
                        throw new OperationCanceledException(token);
                    }
                    Console.WriteLine("Thread:{0} Printing: {1}", System.Threading.Thread.CurrentThread.ManagedThreadId, i++);
                }
            });

            Console.WriteLine("Cancelling task");
            
            tokenSource.Cancel();

 

When tokenSource.Cancel method execute then token.IsCancellationRequested property will gets true then you need to cancel execution of task. In above example I am throwing OperationCanceledException which should have parameter as token, but you need to catch this exception otherwise it will give error “Unhandled Exception”. If you don’t want to throw exception explicitly then you can use ThrowIfCancellationRequested method which internally throw OperationCanceledException and no need to explicitly check for token.IsCancellationRequested property.

	    CancellationTokenSource tokenSource = new CancellationTokenSource();
            CancellationToken token = tokenSource.Token;

            int i = 0;
            Console.WriteLine("Calling from Main Thread {0}", System.Threading.Thread.CurrentThread.ManagedThreadId);
            var task = Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    try
                    {
                        token.ThrowIfCancellationRequested();
                    }
                    catch (OperationCanceledException)
                    {
                        Console.WriteLine("Task cancel detected");
                        break;
                    }
                    Console.WriteLine("Thread:{0} Printing: {1}", System.Threading.Thread.CurrentThread.ManagedThreadId, i++);
                }


            });

            Console.WriteLine("Cancelling task");
            Thread.Sleep(10);
            tokenSource.Cancel();//Cancelling task
           Console.WriteLine("Task Status:{0}", task.Status);

Output

Calling from Main Thread 10

Cancelling task

Thread:6 Printing: 0

Thread:6 Printing: 1

Thread:6 Printing: 2

Thread:6 Printing: 3

Thread:6 Printing: 4

Thread:6 Printing: 5

Thread:6 Printing: 6

Thread:6 Printing: 7

Thread:6 Printing: 8

Thread:6 Printing: 9

Task Status:Running

Task cancel detected

Wait until Task Execution Completed

You can see TaskStatus is showing status as “Running’” in above output besides Cancel method fired before than task status. So to avoid execution next statement after cancel method we should wait for task to be in complete phase for this we can use Wait method of task class.

	Console.WriteLine("Cancelling task");
	Thread.Sleep(10);
        tokenSource.Cancel();
        task.Wait();//wait for thread to completes its execution
        Console.WriteLine("Task Status:{0}", task.Status);

Output

Calling from Main Thread 9

Cancelling task

Thread:6 Printing: 0

Thread:6 Printing: 1

Thread:6 Printing: 2

Thread:6 Printing: 3

Thread:6 Printing: 4

Thread:6 Printing: 5

Task cancel detected

Task Status:RanToCompletion

Cancelling Several Tasks

You can use one instance of token to cancel several tasks like in below example:

public void CancelSeveralTasks()
        {
             CancellationTokenSource tokenSource = new CancellationTokenSource();
            CancellationToken token = tokenSource.Token;

            int i = 0;
            Console.WriteLine("Calling from Main Thread {0}", System.Threading.Thread.CurrentThread.ManagedThreadId);

            Task t1 = new Task(() =>
            {
                while (true)
                {
                    try
                    {
                        token.ThrowIfCancellationRequested();
                    }

                    catch (OperationCanceledException)
                    {
                        Console.WriteLine("Task1 cancel detected");
                        break;
                    }

                    Console.WriteLine("Task1: Printing: {1}", System.Threading.Thread.CurrentThread.ManagedThreadId, i++);
                }
            }, token);

            Task t2 = new Task(() =>
            {
                while (true)
                {
                    try
                    {
                        token.ThrowIfCancellationRequested();
                    }

                    catch (OperationCanceledException)
                    {
                        Console.WriteLine("Task2 cancel detected");
                        break;
                    }

                    Console.WriteLine("Task2: Printing: {1}", System.Threading.Thread.CurrentThread.ManagedThreadId, i++);
                }
            });

            t1.Start();
            t2.Start();
            Thread.Sleep(100);
            tokenSource.Cancel();

            t1.Wait();//wait for thread to completes its execution
            t2.Wait();//wait for thread to completes its execution
            Console.WriteLine("Task1 Status:{0}", t1.Status);
            Console.WriteLine("Task2 Status:{0}", t1.Status);
        }

Output

Calling from Main Thread 9

Task1: Printing: 0

Task1: Printing: 1

Task1: Printing: 2

Task1: Printing: 3

Task1: Printing: 4

Task1: Printing: 5

Task1: Printing: 6

Task1: Printing: 7

Task1: Printing: 8

Task1: Printing: 9

Task1: Printing: 10

Task1: Printing: 11

Task1: Printing: 12

Task1: Printing: 14

Task1: Printing: 15

Task1: Printing: 16

Task1: Printing: 17

Task1: Printing: 18

Task1: Printing: 19

Task2: Printing: 13

Task2: Printing: 21

Task2: Printing: 22

Task2: Printing: 23

Task2: Printing: 24

Task2: Printing: 25

Task2: Printing: 26

Task2: Printing: 27

Task2: Printing: 28

Task2: Printing: 29

Task1: Printing: 20

Task1: Printing: 31

Task1: Printing: 32

Task1: Printing: 33

Task1: Printing: 34

Task2: Printing: 30

Task1: Printing: 35

Task1: Printing: 37

Task1: Printing: 38

Task2: Printing: 36

Task2: Printing: 40

Task2: Printing: 41

Task1: Printing: 39

Task1 cancel detected

Task2 cancel detected

Task1 Status:RanToCompletion

Task2 Status:RanToCompletion

Monitoring Cancellation with a Delegate

You can register delegate to get status of cancellation as callback. This is useful if your task is doing some other asynchronous operations. It can be useful in showing cancellation status on UI.

        public void MonitorTaskwithDelegates()
        {
            CancellationTokenSource tokenSource = new CancellationTokenSource();
            CancellationToken token = tokenSource.Token;

            int i = 0;
            Console.WriteLine("Calling from Main Thread {0}", System.Threading.Thread.CurrentThread.ManagedThreadId);

            Task t1 = new Task(() =>
            {
                while (true)
                {
                    try
                    {
                        token.ThrowIfCancellationRequested();
                    }

                    catch (OperationCanceledException)
                    {
                        Console.WriteLine("Task1 cancel detected");
                        break;
                    }

                    Console.WriteLine("Task1: Printing: {1}", System.Threading.Thread.CurrentThread.ManagedThreadId, i++);
                }
            }, token);

            //Register Cancellation Delegate
            token.Register(new Action(GetStatus));
            t1.Start();
            Thread.Sleep(10);
            //cancelling task
            tokenSource.Cancel();
        }
	public void GetStatus()
        {
            Console.WriteLine("Cancelled called");
        }

Output

Calling from Main Thread 10

Task1: Printing: 0

Task1: Printing: 1

Task1: Printing: 2

Task1: Printing: 3

Task1: Printing: 4

Task1: Printing: 5

Task1: Printing: 6

Task1: Printing: 7

Task1: Printing: 8

Task1: Printing: 9

Task1: Printing: 10

Task1: Printing: 11

Task1: Printing: 12

Cancelled called

Task1 cancel detected

 

I hope this article will help to you to understand Cooperative Cancellation in Parallel tasks.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Powered by WordPress.com.

Up ↑

%d bloggers like this: