How to: Cancel a Task and Its Children
http://msdn.microsoft.com/en-us/library/dd537607.aspx
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks; public class Example
{
public static void Main()
{
var tokenSource = new CancellationTokenSource();
var token = tokenSource.Token; // Store references to the tasks so that we can wait on them and
// observe their status after cancellation.
Task t;
var tasks = new ConcurrentBag<Task>(); Console.WriteLine("Press any key to begin tasks...");
Console.WriteLine("To terminate the example, press 'c' to cancel and exit...");
Console.ReadKey();
Console.WriteLine(); // Request cancellation of a single task when the token source is canceled.
// Pass the token to the user delegate, and also to the task so it can
// handle the exception correctly.
t = Task.Factory.StartNew( () => DoSomeWork(, token), token);
Console.WriteLine("Task {0} executing", t.Id);
tasks.Add(t); // Request cancellation of a task and its children. Note the token is passed
// to (1) the user delegate and (2) as the second argument to StartNew, so
// that the task instance can correctly handle the OperationCanceledException.
t = Task.Factory.StartNew( () => {
// Create some cancelable child tasks.
Task tc;
for (int i = ; i <= ; i++) {
// For each child task, pass the same token
// to each user delegate and to StartNew.
tc = Task.Factory.StartNew( iteration => DoSomeWork((int)iteration, token), i, token);
Console.WriteLine("Task {0} executing", tc.Id);
tasks.Add(tc);
// Pass the same token again to do work on the parent task.
// All will be signaled by the call to tokenSource.Cancel below.
DoSomeWork(, token);
}
},
token); Console.WriteLine("Task {0} executing", t.Id);
tasks.Add(t); // Request cancellation from the UI thread.
if (Console.ReadKey().KeyChar == 'c') {
tokenSource.Cancel();
Console.WriteLine("\nTask cancellation requested."); // Optional: Observe the change in the Status property on the task.
// It is not necessary to wait on tasks that have canceled. However,
// if you do wait, you must enclose the call in a try-catch block to
// catch the TaskCanceledExceptions that are thrown. If you do
// not wait, no exception is thrown if the token that was passed to the
// StartNew method is the same token that requested the cancellation.
} try {
Task.WaitAll(tasks.ToArray());
}
catch (AggregateException e) {
Console.WriteLine("\nAggregateException thrown with the following inner exceptions:");
// Display information about each exception.
foreach (var v in e.InnerExceptions) {
if (v is TaskCanceledException)
Console.WriteLine(" TaskCanceledException: Task {0}",
((TaskCanceledException) v).Task.Id);
else
Console.WriteLine(" Exception: {0}", v.GetType().Name);
}
Console.WriteLine();
} // Display status of all tasks.
foreach (var task in tasks)
Console.WriteLine("Task {0} status is now {1}", task.Id, task.Status);
} static void DoSomeWork(int taskNum, CancellationToken ct)
{
// Was cancellation already requested?
if (ct.IsCancellationRequested == true) {
Console.WriteLine("Task {0} was cancelled before it got started.",
taskNum);
ct.ThrowIfCancellationRequested();
} int maxIterations = ; // NOTE!!! A "TaskCanceledException was unhandled
// by user code" error will be raised here if "Just My Code"
// is enabled on your computer. On Express editions JMC is
// enabled and cannot be disabled. The exception is benign.
// Just press F5 to continue executing your code.
for (int i = ; i <= maxIterations; i++) {
// Do a bit of work. Not too much.
var sw = new SpinWait();
for (int j = ; j <= ; j++)
sw.SpinOnce(); if (ct.IsCancellationRequested) {
Console.WriteLine("Task {0} cancelled", taskNum);
ct.ThrowIfCancellationRequested();
}
}
}
}
// The example displays output like the following:
// Press any key to begin tasks...
// To terminate the example, press 'c' to cancel and exit...
//
// Task 1 executing
// Task 2 executing
// Task 3 executing
// Task 4 executing
// Task 5 executing
// Task 6 executing
// Task 7 executing
// Task 8 executing
// c
// Task cancellation requested.
// Task 2 cancelled
// Task 7 cancelled
//
// AggregateException thrown with the following inner exceptions:
// TaskCanceledException: Task 2
// TaskCanceledException: Task 8
// TaskCanceledException: Task 7
//
// Task 2 status is now Canceled
// Task 1 status is now RanToCompletion
// Task 8 status is now Canceled
// Task 7 status is now Canceled
// Task 6 status is now RanToCompletion
// Task 5 status is now RanToCompletion
// Task 4 status is now RanToCompletion
// Task 3 status is now RanToCompletion
How to: Cancel a Task and Its Children的更多相关文章
- Task C# 多线程和异步模型 TPL模型 【C#】43. TPL基础——Task初步 22 C# 第十八章 TPL 并行编程 TPL 和传统 .NET 异步编程一 Task.Delay() 和 Thread.Sleep() 区别
Task C# 多线程和异步模型 TPL模型 Task,异步,多线程简单总结 1,如何把一个异步封装为Task异步 Task.Factory.FromAsync 对老的一些异步模型封装为Task ...
- 细说.NET中的多线程 (三 使用Task)
上一节我们介绍了线程池相关的概念以及用法.我们可以发现ThreadPool. QueueUserWorkItem是一种起了线程之后就不管了的做法.但是实际应用过程,我们往往会有更多的需求,比如如果更简 ...
- Thread.Sleep vs. Task.Delay
We use both Thread.Sleep() and Task.Delay() to suspend the execution of a program for some given tim ...
- C# 多任务之 Task
Task 是什么 ? Task 是一个类, 它表示一个操作不返回一个值,通常以异步方式执行. Task 对象是一个的中心思想 基于任务的异步模式 首次引入.NET Framework 4 中. 继承层 ...
- .NET 并行(多核)编程系列之五 Task执行和异常处理
原文:.NET 并行(多核)编程系列之五 Task执行和异常处理 .NET 并行(多核)编程系列之五 Task执行和异常处理 前言:本篇主要讲述等待task执行完成. 本篇的议题如下: 1. 等待Ta ...
- .NET 4 并行(多核)编程系列之三 从Task的取消
原文:.NET 4 并行(多核)编程系列之三 从Task的取消 .NET 4 并行(多核)编程系列之三 从Task的取消 前言:因为Task是.NET 4并行编程最为核心的一个类,也我们在是在并行编程 ...
- Task Cancellation: Parallel Programming
http://beyondrelational.com/modules/2/blogs/79/posts/11524/task-cancellation-parallel-programming-ii ...
- .Net4.0 任务(Task)
任务(Task)是一个管理并行工作单元的轻量级对象.它通过使用CLR的线程池来避免启动专用线程,可以更有效率的利用线程池.System.Threading.Tasks 命名空间下任务相关类一览: 类 ...
- C# 多线程之Task(任务
1.简介 为什么MS要推出Task,而不推Thread和ThreadPool,以下是我的见解: (1).Thread的Api并不靠谱,甚至MS自己都不推荐,原因,它将整个Thread类都不开放给W ...
随机推荐
- 远程Servie通信AIDL
不可以直接通过binder了. 1.先编写一个aidl文件,里边包含我们要通信的方法.(Android studio 有直接新建AIDL选项) interface myInterface { /** ...
- CSS——操作css文件
//动态 css文件内容. 修改鼠标经过时行.单元格的背景颜色 function header_rowOrcell_over(divGrid) { var gridopts = divGrid.dat ...
- IP流量重放与pcap文件格式解析
(作者:燕云 出处:http://www.cnblogs.com/SwordTao/ 欢迎转载,但也请保留这段声明,谢谢!) 君不见 黄河之水 天上来 奔流到海不复回 君不见 高堂明镜 悲 ...
- 关于java中的OutOfMemory种类和解决方法
1.OutOfMemory的三种情况 1) 永久区溢出 Exception in thread "main" java.lang.OutOfMemoryError: PermGen ...
- centos7 安装 rabbitmq
主题 因为自己学习项目可能会用到rabbitmq..我又是第一次学习.以前没安装过.所以简单记录下我在centos7环境下安装rabbitmq的过程步骤,下次可以参考. 步骤 1.杂七杂八的东西 安装 ...
- 取消Eclipse的js校验功能
1 window>>preferences>>javascript>>validator>>Error/warnings 去掉 Enable Javas ...
- 【原】Coursera—Andrew Ng机器学习—Week 7 习题—支持向量机SVM
[1] [2] Answer: B. 即 x1=3这条垂直线. [3] Answer: B 因为要尽可能小.对B,右侧红叉,有1/2 * 2 = 1 ≥ 1,左侧圆圈,有1/2 * -2 = -1 ...
- SQLSERVER2012误删数据恢复过程
由于长时间从事企业应用系统开发,前往用户现场升级.调试系统是比较常做的事情,但是就在周一,由于同事的失误在毫无知觉的情况下误删了生产数据库几乎所有的数据.当我发现的那一刻,感觉头发都立起来了,心想这他 ...
- 【hdu4135】【hdu2841】【hdu1695】一类通过容斥定理求区间互质的方法
[HDU4135]Co-prime 题意 给出三个整数N,A,B.问在区间[A,B]内,与N互质的数的个数.其中N<=10^9,A,B<=10^15. 分析 容斥定理的模板题.可以通过容斥 ...
- Quaternion.identity是什么意思?
Quaternion.identity就是指Quaternion(0,0,0,0),