Parallel Programming-use CancellationTokenSource to schedule Parallel tasks and parallelprogramming

Source: Internet
Author: User

Parallel Programming-use CancellationTokenSource to schedule Parallel tasks and parallelprogramming

This article describes how to use CancellationTokenSource to schedule tasks that run in parallel.

I. Application scenarios

When multiple tasks run in parallel, if an exception occurs in the program running one of the tasks, we want to terminate all tasks to be executed immediately. This will benefit the system performance and other aspects.

Ii. Code executed by multiple threads in source code 2.1
   public class Handler    {        public void DoSomething(CancellationTokenSource cts, int index)        {            if (cts.IsCancellationRequested)            {                return;            }            if (index == 2)            {                cts.Cancel();            }            Console.WriteLine(index);        }    }

Two points:

2.2 Task scheduling code
 public class AppClient    {        public static void Main()        {            var cts = new CancellationTokenSource();            var childTasks = new List<Task>();            var parentTask = new Task(() =>            {                var taskFactory = new TaskFactory(cts.Token, TaskCreationOptions.AttachedToParent,                    TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default);                for (var i = 0; i < 100; i++)                {                    var tempIndex = i;                    var childTask = taskFactory.StartNew(() => new Handler().DoSomething(cts, tempIndex));                    childTasks.Add(childTask);                }                foreach (var task in childTasks)                {                    task.ContinueWith(t => cts.Cancel(), TaskContinuationOptions.OnlyOnFaulted);                }            });            parentTask.Start();            parentTask.Wait();            Console.Read();        }    }

The above code will normally generate 100 tasks and Attach them to the parent Task, which is uniformly scheduled by the parent Task (parentTask. Start; parentTask. Wait)

2.3 Task. ContinueWith
foreach (var task in childTasks){      task.ContinueWith(t => cts.Cancel(), TaskContinuationOptions.OnlyOnFaulted);}

The main meaning of this Code is that when a task error occurs, for example, when an exception is thrown, the cts is canceled. After the cts is canceled (IsCancellationRequested = true), the subsequent operations will be directly returned and will not be executed.

This is back to the topic at the beginning of this article: when multiple tasks run in parallel, if one of the tasks runs an exception in the program, we want to terminate all the tasks to be executed immediately. This will benefit the system performance and other aspects.

Parallel Programming is intended to write a series of articles to sum up.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.