Technology Corner

Home » DotNet » Task Cancellation: Parallel Programming – III

Task Cancellation: Parallel Programming – III

Enter your email address to follow this blog and receive notifications of new posts by email.

Join 80 other followers

Twitter updates

Archives

RSS InfoQ Feeds

  • How Google Develops New Managers
    Alex Langshur, host of Google Partners Podcasts, has organized the podcast Google HR secrets: identifying & developing great managers, interviewing Sarah Calderon, People Development at Google, on how Google selects, trains, and develops their managers. By Abel Avram
  • Presentation: Cognitive Services, Next Step in Creating Our Robot Overlords
    Harold Pulcher discusses Cognitive Services, how to get started using them, and how to incorporate speech, image, and facial recognition into an application. By Harold Pulcher
  • Presentation: Control Flow Integrity Using Hardware Counters
    Jamie Butler and Cody Pierce discuss a new system for early detection and prevention of unknown exploits. Their system uses Performance Monitoring Unit hardware to enforce coarse-grained Control Flow Integrity (CFI). They intend to prove that their approach is effective and suitable for practical use, while staying resistant to bypass. By Jamie Butler
  • JetBrains Launches GoLand Go IDE
    JetBrains has moved its Go IDE from its early access programme to market. Now branded as GoLand, the IDE extends the IntelliJ platform making its core functionality specific to Go. This follows suit with their other language-specific tools such as PyCharm for Python and RubyMine for Ruby. By Andrew Morgan
  • Panel on the Future of AI
    An SF QCon panel on the future of AI explored some issues facing machine learning today. The areas explored: critical issues facing AI right now, how has technology changed the way people are hired, how non-leading edge companies make the best use of current technologies, what the role of humans in relation to AI is, and exciting new breakthroughs on the imm […]
  • Microsoft Updates Cosmos DB with Cassandra Support and Provides Better Availability Guarantees
    Last month at Microsoft Connect 2017, Azure Cosmos DB received several new updates, including support for using the Cassandra NoSQL database API and increased guarantees for availability. With the Cassandra NoSQL database API, customers can run operations inside Cosmos DB on a data model. The availability guarantee moves from 99.99 percent to 99.999 percent. […]
  • Article: Approximate Computing on WSO2: Explaining Approximation Algorithms in an Applied Setting
    In this article, we describe an example real world application of API monitoring which gets benefit by using approximate stream processing. We developed the application on top of WSO2 Stream Processor as Siddhi extension. Siddhi is the complex event processing library which acts as the event processing engine of WSO2 Stream Processor. By Chamod Samarajeewa
  • Rust in Visual Studio and VS Code
    Daniel Griffen has released a preview version of a Rust language service for Visual Studio. This plugin requires Visual Studio 2017 Preview, an experimental release stream for testing new VS features. By Jonathan Allen
  • Article: Key Takeaway Points and Lessons Learned from QCon San Francisco 2017
    The eleventh annual QCon San Francisco was the biggest yet, bringing together over 1,800 team leads, architects, project managers, and engineering directors. By Abel Avram
  • Article: Q&A With Eberhard Wolff On the Book “A Practical Guide to Continuous Delivery”
    Eberhard Wolff speaks with InfoQ about his work "Continuous Delivery: A Practical Guide", where we detail some of the major concepts behind successful CD adoption and the ripple-effect it can have on developer productivity and quality of service. By Dylan Raithel

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

Blogs I Follow

%d bloggers like this: