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 ...
随机推荐
- 「小程序JAVA实战」springboot的后台搭建(30)
转自:https://idig8.com/2018/08/27/xiaochengxujavashizhanspringbootdehoutaidajian30/ 做了多年的开发,原来很多项目都是一个 ...
- Delphi IOS 后台定时器
3.这里有一个问题,就是客户端是通过心跳来和服务端保持连接,心跳是由定时器触发的,当我退到后台以后,定时器方法被挂起,那么通过如下设置来在后台运行定时器 beginBackgroundTaskWith ...
- linux系统构架 - LB集群之LVS介绍
LB 集群是 load balance 集群的简写,翻译成中文就是负载均衡集群.常用的负载均衡开源软件有 nginx.lvs.keepalived ,商业的硬件负载设备 F5.Netscale. LB ...
- Kettle中配置oracle RAC
由于项目中使用了oracle v-ip做了oracle数据库集群,现在需要把项目中程序进行升级. 原来的程序中直接使用的是JDBC然后配置的kettle.properties配置文件,如下图: 根据项 ...
- Ubuntu 15.04 开机无法进入图形界面,自动进入emergency mode解决方法
原因:关机的时候没有正常退出,直接强制关机了... 解决: 就是在那个GIVE root password for maintenance (or type control-D to continue ...
- fdsf
https://blog.csdn.net/chen_2890/article/details/83757022Elasticsearch环境搭建和介绍(Windows) https://blog.c ...
- 使用C#通过Oracle.DataAccess连接Oracle,部署时需要注意版本问题
平时我们开发使用的是32位的PC机,所以安装的也是Oracle32位的客户端.但是一般服务器都是64位的,安装的也是64位的Oracle客户端,如果要部署使用Oracle.DataAccess连接Or ...
- 201671010140. 2016-2017-2 《Java程序设计》java学习第九周
第七章:<异常,断言和日志>知识点小结 本周,进行了对Java中的异常处理的了解学习,以下是部分所得. 一.未检查异常与已检查异常的区别: 未检查异常处理方法:1.捕获2.继续 ...
- css的优先级和权重问题 以及!important优先级
一,前言: 刚加的css怎么没有渲染出来?浏览器中查看,发现是被其他的css给覆盖了,相信我们都曾遇到过这样的问题.那么浏览器是如何选择css标签的渲染顺序的呢?换句话说,css选择器的优先级是怎么规 ...
- php设置错误,错误记录
//设置错误级别. error_reporting(E_ALL); //显示所有错误 error_reporting(E_ALL&~E_NOTICE); //显示所有错误但不显示提示级别的 ...