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的更多相关文章

  1. 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 ...

  2. 细说.NET中的多线程 (三 使用Task)

    上一节我们介绍了线程池相关的概念以及用法.我们可以发现ThreadPool. QueueUserWorkItem是一种起了线程之后就不管了的做法.但是实际应用过程,我们往往会有更多的需求,比如如果更简 ...

  3. Thread.Sleep vs. Task.Delay

    We use both Thread.Sleep() and Task.Delay() to suspend the execution of a program for some given tim ...

  4. C# 多任务之 Task

    Task 是什么 ? Task 是一个类, 它表示一个操作不返回一个值,通常以异步方式执行. Task 对象是一个的中心思想 基于任务的异步模式 首次引入.NET Framework 4 中. 继承层 ...

  5. .NET 并行(多核)编程系列之五 Task执行和异常处理

    原文:.NET 并行(多核)编程系列之五 Task执行和异常处理 .NET 并行(多核)编程系列之五 Task执行和异常处理 前言:本篇主要讲述等待task执行完成. 本篇的议题如下: 1. 等待Ta ...

  6. .NET 4 并行(多核)编程系列之三 从Task的取消

    原文:.NET 4 并行(多核)编程系列之三 从Task的取消 .NET 4 并行(多核)编程系列之三 从Task的取消 前言:因为Task是.NET 4并行编程最为核心的一个类,也我们在是在并行编程 ...

  7. Task Cancellation: Parallel Programming

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

  8. .Net4.0 任务(Task)

    任务(Task)是一个管理并行工作单元的轻量级对象.它通过使用CLR的线程池来避免启动专用线程,可以更有效率的利用线程池.System.Threading.Tasks 命名空间下任务相关类一览: 类 ...

  9. C# 多线程之Task(任务

      1.简介 为什么MS要推出Task,而不推Thread和ThreadPool,以下是我的见解: (1).Thread的Api并不靠谱,甚至MS自己都不推荐,原因,它将整个Thread类都不开放给W ...

随机推荐

  1. linux anaconda 管理 python 包

    1.下载 anaconda https://www.continuum.io/downloads 2.安装anaconda 3.conda install package-name //利用anaco ...

  2. openLayers 3 之入门

    openLayers 3 之入门 openlayer是web GIS客户端开发提供的javascript类库,也是开源框架,可以加载本地数据进行展示地图 1.下载相关引用的js.css文件 2.类似于 ...

  3. leetcode836

    public class Solution { public bool IsRectangleOverlap(int[] rec1, int[] rec2) { ], rec2[]) < Mat ...

  4. Bower 使用

    Bower:客户端库管理工具 来自<JavaScript 标准参考教程(alpha)>,by 阮一峰 目录 概述 常用操作 项目初始化 库的安装 库的搜索和查看 库的更新和卸载 列出所有库 ...

  5. 【转】Unity3d:读取FBX中的动画

    从模型中获得切割好的动画clip,并且对其中设置好的动画事件进行修改方法: 1.动画模型后缀为.FBX.在Unity3d中,能够显示FBX中的动画.要加载模型中的AnimationClip,只要Ass ...

  6. IOS 键盘的显示与关闭

    在每一个IOS应用中,几乎不可避免的要进行文本输入操作,例如要求用户填写登陆注册信息,进行话题的评论回复,等等.用到的文本输入组件有UITextField,UITextView,对于这两个组件的相关属 ...

  7. 使用Eclipse搭建JavaWeb开发环境的几个基本问题

    Eclipse搭建JavaWeb开发环境 eclipse是一个用于java程序开发的ide软件,tomcat是一个运行javaweb应用的服务器软件,使用eclipse开发javaweb应用的时,首要 ...

  8. drbd switch off

    DRBD secondary to primary: drbdadm disconnect all drbdadm primary r0 --force mount /dev/drbd0 /mnt [ ...

  9. java 蓝桥杯基础练习 01字串 进制转换

    问题描述 对于长度为5位的一个01串,每一位都可能是0或1,一共有32种可能.它们的前几个是: 请按从小到大的顺序输出这32种01串. 输入格式 本试题没有输入. 输出格式 输出32行,按从小到大的顺 ...

  10. pyinstaller打包后运行提示找不到模块

    截止到2017年9月20号,pyinstaller只支持到python3.5,如果需要支持到3.6,需要自己在github上下载pyinstaller的开发版. 在打包时候,并没有提示错误,可以顺利打 ...