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 ...
随机推荐
- LR11中webservice协议的性能测试应用
使用LR11对webservice协议的接口测试应用 脚本开发步骤:1.打开vuser generator,新建一个脚本,选择webservice协议:2.选择Manage Services(服务管理 ...
- 读《分布式一致性原理》CURATOR客户端
创建会话 使用curator客户端创建会话和其它客户端产品有很大不同 1.使用CuratorFrameworkFactory这个工厂类的两个静态方法来创建一个客户端: public static Cu ...
- firefox 插件 取消认证签名
Firebug Tab Mix plus :系统退出自动保存tab List. tab mix options>Session>start/exit>when browse ...
- 第1章WCF简介(WCF全面解析读书笔记2)
第1章 WCF简介 面向服务架构(SOA)是近年来备受业界关注的一个主题,它代表了软件架构的一种方向.顺应SOA发展潮流,微软于2006年年底推出了一种新的分布式通信框架Windows Communi ...
- GetHashCode()
[GetHashCode] GetHashCode 方法的默认实现不保证针对不同的对象返回唯一值.而且,.NET Framework 不保证 GetHashCode 方法的默认实现以及它所返回的值在不 ...
- 使用opencv-python画OpenCV LOGO
OpenCV2-Python 官方教程的练习 代码: #-*- coding:utf-8 -*- import numpy as np import cv2 img = np.zeros((512, ...
- FP寻源报错
ERROR [HY000] [Oracle][ODBC][Ora]ORA-01114: IO error writing block to file (block # ) ORA-01114: I ...
- 欲望都市游戏设计 背景图层和UI图层的设计
- 解决"authentication token manipulation error"
昨天安装是Ubuntu Server. 配置好了几个软件后就忘记继续了...今天打开,居然忘记了密码...真是的.. 后来还是要改了. 不想重新弄什么的了..百度了下怎么改密码...然后就有一篇 ...
- 523. Continuous Subarray Sum是否有连续和是某数的几倍
[抄题]: Given a list of non-negative numbers and a target integer k, write a function to check if the ...