Getting Started with Adobe After Effects - Part 6: Motion Blur


Upload Image Close it
Select File

Browse by Tags · View All
#DOTNET 33
#.NET 26
#ASP.NET 25
ASP.NET 24
brh 22
#C# 14
.NET 13
WCF 11
c# 9
#MultiThreading 7

Archive · View All
January 2011 10
September 2011 6
May 2011 6
December 2011 5
October 2011 5
June 2011 5
February 2011 3
November 2012 2
August 2012 2
April 2012 2

Task Cancellation: Parallel Programming - III

Jan 29 2011 7:18PM by Neeraj Kaushik   

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.

You can also get source code above examples here:

Tags: #.NET, #DOTNET, #Parallel Programming, brh,


Neeraj Kaushik
53 · 4% · 1132
1
 
0
Lifesaver
 
0
Refreshed
 
0
Learned
 
0
Incorrect



Submit

Your Comment


Sign Up or Login to post a comment.

"Task Cancellation: Parallel Programming - III" rated 5 out of 5 by 1 readers
Task Cancellation: Parallel Programming - III , 5.0 out of 5 based on 1 ratings
    Copyright © Rivera Informatic Private Ltd Contact us      Privacy Policy      Terms of use      Report Abuse      Advertising      [ZULU1097]