http://beyondrelational.com/modules/2/blogs/79/posts/11524/task-cancellation-parallel-programming-iii.aspx

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

01.CancellationTokenSource tokenSource = newCancellationTokenSource();
02.CancellationToken token = tokenSource.Token;
03. 
04.int i = 0;
05.Console.WriteLine("Calling from Main Thread {0}", System.Threading.Thread.CurrentThread.ManagedThreadId);
06.var task = Task.Factory.StartNew(() =>
07.{
08.while (true)
09.{
10.if (token.IsCancellationRequested)
11.{
12.Console.WriteLine("Task cancel detected");
13.throw new OperationCanceledException(token);
14.}
15.Console.WriteLine("Thread:{0} Printing: {1}", System.Threading.Thread.CurrentThread.ManagedThreadId, i++);
16.}
17.});
18. 
19.Console.WriteLine("Cancelling task");
20. 
21.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 throwingOperationCanceledException 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 throwOperationCanceledException and no need to explicitly check for token.IsCancellationRequested property.

01.CancellationTokenSource tokenSource = newCancellationTokenSource();
02.CancellationToken token = tokenSource.Token;
03. 
04.int i = 0;
05.Console.WriteLine("Calling from Main Thread {0}", System.Threading.Thread.CurrentThread.ManagedThreadId);
06.var task = Task.Factory.StartNew(() =>
07.{
08.while (true)
09.{
10.try
11.{
12.token.ThrowIfCancellationRequested();
13.}
14.catch (OperationCanceledException)
15.{
16.Console.WriteLine("Task cancel detected");
17.break;
18.}
19.Console.WriteLine("Thread:{0} Printing: {1}", System.Threading.Thread.CurrentThread.ManagedThreadId, i++);
20.}
21. 
22. 
23.});
24. 
25.Console.WriteLine("Cancelling task");
26.Thread.Sleep(10);
27.tokenSource.Cancel();//Cancelling task
28.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.

1.Console.WriteLine("Cancelling task");
2.Thread.Sleep(10);
3.tokenSource.Cancel();
4.task.Wait();//wait for thread to completes its execution
5.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:

01.public void CancelSeveralTasks()
02.{
03.CancellationTokenSource tokenSource = newCancellationTokenSource();
04.CancellationToken token = tokenSource.Token;
05. 
06.int i = 0;
07.Console.WriteLine("Calling from Main Thread {0}", System.Threading.Thread.CurrentThread.ManagedThreadId);
08. 
09.Task t1 = new Task(() =>
10.{
11.while (true)
12.{
13.try
14.{
15.token.ThrowIfCancellationRequested();
16.}
17. 
18.catch (OperationCanceledException)
19.{
20.Console.WriteLine("Task1 cancel detected");
21.break;
22.}
23. 
24.Console.WriteLine("Task1: Printing: {1}", System.Threading.Thread.CurrentThread.ManagedThreadId, i++);
25.}
26.}, token);
27. 
28.Task t2 = new Task(() =>
29.{
30.while (true)
31.{
32.try
33.{
34.token.ThrowIfCancellationRequested();
35.}
36. 
37.catch (OperationCanceledException)
38.{
39.Console.WriteLine("Task2 cancel detected");
40.break;
41.}
42. 
43.Console.WriteLine("Task2: Printing: {1}", System.Threading.Thread.CurrentThread.ManagedThreadId, i++);
44.}
45.});
46. 
47.t1.Start();
48.t2.Start();
49.Thread.Sleep(100);
50.tokenSource.Cancel();
51. 
52.t1.Wait();//wait for thread to completes its execution
53.t2.Wait();//wait for thread to completes its execution
54.Console.WriteLine("Task1 Status:{0}", t1.Status);
55.Console.WriteLine("Task2 Status:{0}", t1.Status);
56.}

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.

01.public void MonitorTaskwithDelegates()
02.{
03.CancellationTokenSource tokenSource = newCancellationTokenSource();
04.CancellationToken token = tokenSource.Token;
05. 
06.int i = 0;
07.Console.WriteLine("Calling from Main Thread {0}", System.Threading.Thread.CurrentThread.ManagedThreadId);
08. 
09.Task t1 = new Task(() =>
10.{
11.while (true)
12.{
13.try
14.{
15.token.ThrowIfCancellationRequested();
16.}
17. 
18.catch (OperationCanceledException)
19.{
20.Console.WriteLine("Task1 cancel detected");
21.break;
22.}
23. 
24.Console.WriteLine("Task1: Printing: {1}", System.Threading.Thread.CurrentThread.ManagedThreadId, i++);
25.}
26.}, token);
27. 
28.//Register Cancellation Delegate
29.token.Register(new Action(GetStatus));
30.t1.Start();
31.Thread.Sleep(10);
32.//cancelling task
33.tokenSource.Cancel();
34.}
35.public void GetStatus()
36.{
37.Console.WriteLine("Cancelled called");
38.}

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:

Task Cancellation: Parallel Programming的更多相关文章

  1. Fork and Join: Java Can Excel at Painless Parallel Programming Too!---转

    原文地址:http://www.oracle.com/technetwork/articles/java/fork-join-422606.html Multicore processors are ...

  2. Notes of Principles of Parallel Programming - TODO

    0.1 TopicNotes of Lin C., Snyder L.. Principles of Parallel Programming. Beijing: China Machine Pres ...

  3. Samples for Parallel Programming with the .NET Framework

    The .NET Framework 4 includes significant advancements for developers writing parallel and concurren ...

  4. C#并行开发_Thread/ThreadPool, Task/TaskFactory, Parallel

    大家好,本次讨论的是C#中的并行开发,给力吧,随着并行的概念深入,哥也赶上这个潮流了,其实之前讨论C#的异步调用或者C#中BeginInvoke或者Invoke都已经涉及了部分本篇的内容. 参考书目: ...

  5. Introduction to Multi-Threaded, Multi-Core and Parallel Programming concepts

    https://katyscode.wordpress.com/2013/05/17/introduction-to-multi-threaded-multi-core-and-parallel-pr ...

  6. A Pattern Language for Parallel Programming

    The pattern language is organized into four design spaces.  Generally one starts at the top in the F ...

  7. 4.3 Reduction代码(Heterogeneous Parallel Programming class lab)

    首先添加上Heterogeneous Parallel Programming class 中 lab: Reduction的代码: myReduction.c // MP Reduction // ...

  8. .NET 异步多线程,Thread,ThreadPool,Task,Parallel,异常处理,线程取消

    今天记录一下异步多线程的进阶历史,以及简单的使用方法 主要还是以Task,Parallel为主,毕竟用的比较多的现在就是这些了,再往前去的,除非是老项目,不然真的应该是挺少了,大概有个概念,就当了解一 ...

  9. Parallel Programming for FPGAs 学习笔记(1)

    Parallel Programming for FPGAs 学习笔记(1)

随机推荐

  1. 自动删除超过30天文件的vbs脚本【转发】

    利用代码制作自动删除超过30天的文件及文件夹的vbs脚本,定期清理文件夹中长时间无用文件. 1.首先在新建一个文本文档,粘贴代码(代码可通过添加微信公众号vbs_edit(VBS脚本之家)回复018获 ...

  2. shell编程之服务脚本编写,文件锁以及信号捕获

    shell脚本编程是linux运维工程师必备的技能,也是非常重要的一个技能,所以把shell编程学好,只有好处.基础语法我也就不讲了,学过C语言这些语言的,稍微看一下就能明白shell编程的基础,所以 ...

  3. Qt Creator下载和安装(详细教程)

    简介 Qt是跨平台的图形开发库,目前由Digia全资子公司 Qt Company 独立运营,官方网址: http://www.qt.io/ 也可以访问Qt项目域名:http://qt-project. ...

  4. 快速玩转Apple Pay开发

    快速玩转Apple Pay开发 更新时间:2016年02月20日09时25分 来源:传智播客 Apple Pay 2016年2月18日上午,苹果公司宣布,与中国银联达成合作,正式在中国大陆上线Appl ...

  5. WPF中CheckBox三种状态打勾打叉和滑动效果

    本文分为两个demo, 第一个demo实现checkBox的打叉或打勾的效果: 第二个demo部分实现checkBox的滑动效果. Demo1: wpf的CheckBox支持三种状态,但是美中不足的是 ...

  6. 【经典dp】 poj 3671

    开一个dp[30010][3]的数组 其中dp[i][j]表示把第i个数改成j最少要花多少次 那么状态转移方程就列出来了: 令a=1 j!=a[i] 0 j==a[i] 那么dp[i][1]=dp[i ...

  7. jquer 带左右按钮滚动图片 点击显示大图

    <style> ul{ list-style:none; padding:0px; margin:0px;} li{ list-style:none; padding:0px; margi ...

  8. sql/plus 常用操作

    一.sys用户和system用户Oracle安装会自动的生成sys用户和system用户(1).sys用户是超级用户,具有最高权限,具有sysdba角色,有create database的权限,该用户 ...

  9. - (void)addAnimation:(CAAnimation *)anim forKey:(nullable NSString *)key; 方法浅析

    转载自:http://blog.csdn.net/ronaldo_carry/article/details/49070119 将viewdidload里面的代码全部注释掉 - (void)viewD ...

  10. this的应用

    <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content ...