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

  • Article: Q&A on the Book "Humans vs Computers"
    Author Gojko Adzic has released a book, Humans vs Computers in which he tells stories about the impact of inflexible automation, edge cases and software bugs on the lives of real people. He explains the common mistakes built into the systems and provides advice on how to prevent these mistakes from being built into our systems in the first place. By Shane Ha […]
  • Q&A with Michael Coté on Devops Adoption and his Talk at DevOpsDays NZ
    Raf Gemmail talks to Pivotal’s Michael Coté about obstacles to DevOps adoption and his forthcoming talk at DevOpsDays NZ 2017 By Rafiq Gemmail
  • TensorFlow Serving 1.0 Release Detailed at Google I/O
    Google's Noah Fiedel details new programming model for TensorFlow Serving in a stable 1.0 release. Subject matter addresses common challenges with portability, servablility , and reproducibility improvements. By Dylan Raithel
  • First NetBeans Code Drop Lands at Apache
    Oracle has released the first of three NetBeans code drops to the Apache Incubator. By Matt Raible
  • Article: The Top 10 Adages in Continuous Deployment
    On the basis of discussions at the Continuous Deployment Summit, researchers derived 10 adages about continuous-deployment practices. These adages represent a working set of approaches and beliefs that guide current practice and establish a tangible target for empirical validation. By Chris Parnin
  • Podcast: Joshua Kerievsky and Heidi Helfand on High Performance via Psychological Safety
    In this podcast Shane Hastie, Lead Editor for Culture & Methods, spoke to Joshua Kerievsky, CEO of Industrial Logic, and Heidi Helfand, Director of Engineering Excellence at Procore Technologies and author of the book Dynamic Reteaming, about their talk High Performance via Psychological Safety. By Joshua Kerievsky
  • Spotify and Google Release Forseti GCP Security Tools
    Google has opened up Forseti Security, a set open source tools for GCP security, to all GCP users. The project is the result of a collaborative effort from both Spotify and Google, combining what was originally separate work together into a single toolkit. It aims to automate security processes for developers in order for them to develop more freely. By Andr […]
  • Article: Q&A on the Book SAFe Distilled
    The book SAFe Distilled breaks down the complexity of the framework into easily understood explanations and actionable guidance. It’s a resource for acquiring a deep understanding of the Scaled Agile Framework, and how to implement it successfully. By Ben Linders
  • String Interpolation in Entity Framework Raises Concerns
    One of the new features in Entity Framework Core 2 is the ability to automatically convert interpolated strings into parameterized SQL. Though designed to avoid problems with poorly written SQL, it is feared that it may actually lead to more SQL injection attacks. By Jonathan Allen
  • Podcast: Twitter's Yao Yue on Latency, Performance Monitoring, & Caching at Scale
    Yao Yue spent the majority of her career working on caching systems at Twitter. She created a performance team that deals with edge performance outliers often exposed by the enormous scale of Twitter. In this podcast, she discusses standing up the performance team, thoughts on instrumenting applications, and interesting performance issues (and strategies for […]

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: