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.