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 ...
随机推荐
- AJAX跨域调用ASP.NET MVC的问题及解决方案
AJAX跨域调用ASP.NET MVC的问题及解决方案 问题描述: 解决方法: 只需要在web.config中添加如下标为红色的内容即可: <system.webServer> <h ...
- [iOS]UIScrollView左右拨动,第二页宽度只有一半问题
用UIScrollView动态加入新View,而这个View是Xib方式创建,如果设置view的frame,这个view的宽度却只有设置的一半,很奇怪.于是我只设置view的frame的x值,不设置整 ...
- NHibernate注意事项
1.检查映射文件是否正确 2.检查配置文件的“嵌入的资源”选项 3.检查Configuration是否加载了程序集
- python 中类的初始化过程
首先元类中的__new__被调用 所有使用该元类的类都会调用一次,不管其有没有初始化,所以元类__new__的作用是修改/验证类的定义 返回的是一个元类的实例,即一个类的定义 元类的__init__由 ...
- faster-rcnn训练自己的数据集参考文章
https://www.cnblogs.com/CarryPotMan/p/5390336.html
- 554. Brick Wall最少的穿墙个数
[抄题]: There is a brick wall in front of you. The wall is rectangular and has several rows of bricks. ...
- 对比Nginx配置文件差异
一.概要: Python2 官方文档:https://docs.python.org/2/library/difflib.html Python2 官方文档:https://docs.python.o ...
- 无法访问windows安装服务。发生这种情况的可能是您在安全模式下运行windows,或是没有正确安装windows安装,。请与技术支持人员联系以获得帮助。
解决办法: 1.命令提示符下输入:msiexec/regserver 2.在“管理工具”→“服务”中启动windows Installer 程序员的基础教程:菜鸟程序员
- rsyslog收集nginx日志配置
rsyslog日志收集配置 rsyslog服务器收集各服务器的日志,并汇总,再由logstash处理 请查看上一篇文章 http://bbotte.blog.51cto.com/6205307/16 ...
- VisualVM远程连接Tomcat(转)
转自:http://www.cnblogs.com/sunshine-2015/p/5547128.html VisualVM VisualVm是一个将很多JDK命令工具可视化的windows程序,直 ...