c# Task编程一个task抛出异常后怎么取消其他线程
从MSDN的Forum上看到别人提供的解决方案,感觉还是比较靠谱,所以就保存下来。
CancellationTokenSource cts = new CancellationTokenSource();
Task t1 = Task.Factory.StartNew(() =>
{
if (!cts.IsCancellationRequested)
{
try
{
//task body that may throw
Console.WriteLine("Task1");
}
catch
{
cts.Cancel();
throw new OperationCanceledException(cts.Token); //the task final state will be Cancelled
//the exception can be ignored if needed
}
if (cts.IsCancellationRequested)
{
//depending on the scenario
//ignore any computed result, do not persist any data, revert all changes
}
}
}, cts.Token);
Task t2 = Task.Factory.StartNew(() =>
{
if (!cts.IsCancellationRequested)
{
try
{
//task body that may throw
Console.WriteLine("Task2");
}
catch
{
cts.Cancel();
throw new OperationCanceledException(cts.Token); //the task final state will be Cancelled
}
if (cts.IsCancellationRequested)
{
//depending on the scenario
//ignore any computed result, do not persist any data, revert all changes
}
}
}, cts.Token);
2. In case that you would like to avoid try/catch in every body you could use a Task Continuation approach like below. However with this approach, the application will pay the price of new tasks being created. At the same time the Cancellation will be delayed.
CancellationTokenSource cts = new CancellationTokenSource();
Task t1 = Task.Factory.StartNew(() =>
{
if (!cts.IsCancellationRequested)
{
//task body that may throw
Console.WriteLine("Task1");
if (cts.IsCancellationRequested)
{
//depending on the scenario
//ignore any computed result, do not persist any data, revert all changes
}
}
}, cts.Token).ContinueWith((task) =>
{
cts.Cancel();
//observe the exception
Exception ex = task.Exception;
}, TaskContinuationOptions.OnlyOnFaulted|TaskContinuationOptions.ExecuteSynchronously );
Task t2 = Task.Factory.StartNew(() =>
{
if (!cts.IsCancellationRequested)
{
//task body that may throw
Console.WriteLine("Task2");
if (cts.IsCancellationRequested)
{
//depending on the scenario
//ignore any computed result, do not persist any data, revert all changes
}
}
}, cts.Token).ContinueWith((task) =>
{
cts.Cancel();
//observe the exception
Exception ex = task.Exception;
}, TaskContinuationOptions.OnlyOnFaulted | TaskContinuationOptions.ExecuteSynchronously);
参考,转载:
https://social.msdn.microsoft.com/Forums/vstudio/en-US/2cbe1fa7-c7dd-4e88-8773-2e3bb1665e2e/how-to-cancel-other-task-when-there-is-an-exception-in-one-of-the-task?forum=parallelextensions
c# Task编程一个task抛出异常后怎么取消其他线程的更多相关文章
- 转载 .Net多线程编程—任务Task https://www.cnblogs.com/hdwgxz/p/6258014.html
.Net多线程编程—任务Task 1 System.Threading.Tasks.Task简介 一个Task表示一个异步操作,Task的创建和执行是独立的. 只读属性: 返回值 名称 说明 ob ...
- .Net多线程编程—任务Task
1 System.Threading.Tasks.Task简介 一个Task表示一个异步操作,Task的创建和执行是独立的. 只读属性: 返回值 名称 说明 object AsyncState 表示在 ...
- java并发编程实战:第七章----取消与关闭
Java没有提供任何机制来安全地终止线程(虽然Thread.stop和suspend方法提供了这样的机制,但由于存在缺陷,因此应该避免使用 中断:一种协作机制,能够使一个线程终止另一个线程的当前工作 ...
- 一个 Task 不够,又来一个 ValueTask ,真的学懵了!
一:背景 1. 讲故事 前几天在项目中用 MemoryStream 的时候意外发现 ReadAsync 方法多了一个返回 ValueTask 的重载,真是日了狗了,一个 Task 已经够学了,又来一个 ...
- C#并发编程-2 异步编程基础-Task
一 异步延迟 在异步方法中,如果需要让程序延迟等待一会后,继续往下执行,应使用Task.Delay()方法. //创建一个在指定的毫秒数后完成的任务. public static Task Delay ...
- .NET 中 如果一个Task A正在await另一个Task B,那么Task A是什么状态
新建一个.NET Core控制台程序,输入如下代码: using System; using System.Threading; using System.Threading.Tasks; class ...
- c# 写着玩的,两个Task并发,一个写队列一个读队列的异常情况
class Program { class TestEnqueue { static Queue<string> str = new Queue<string>(); publ ...
- 临远大神,你为啥要建立一个 TASK表。HumanTaskDTO
临远大神,你为啥要建立一个 TASK表.HumanTaskDTO HumanTask这张表的作用是什么. 为了实现理想中的任务中心.TaskCenter. 首先,工作流可能会完全不包含任何人工节点,全 ...
- 【C# Task】 ValueTask/Task<TResult>
概要 1.如果异步方法的使用者使用 Task.WhenAll 或 Task.WhenAny,则在异步方法中使用 ValueTask<T> 作为返回类型可能会产生高昂的成本.这是因为您需要使 ...
随机推荐
- win7硬盘安装ubuntu双系统——注意项
WIN7 下硬盘安装ubuntu 12.04 博客分类: ubuntu 仅为网络上的资料整理 资料引用:http://www.ctocio.com.cn/35/12325035.shtml htt ...
- asp.net webform杂记
context.Response.ContentType = "text/plain"; string encodeFileName = HttpUtilit ...
- Capabilities and Limitations of Optimizing Compilers
Computer Systems A Programmer's Perspective Second Edition #include <stdio.h> main(){ int wr; ...
- Linux core 文件介绍
Linux core 文件介绍 http://www.cnblogs.com/dongzhiquan/archive/2012/01/20/2328355.html 1. core文件的简单介绍在一个 ...
- 将ntfs分区转换为ext4分区
转自 http://blog.csdn.net/nianhongmin/article/details/27818195 将ntfs分区转换为ext4分区 分类: Linux 2014-05-31 1 ...
- C++用数组实现的静态队列
#ifndef _STATIC_QUEUE_H_ #define _STATIC_QUEUE_H_ // 静态queue模板,用数组实现的队列,在初始化的时候需要指定长度 template<cl ...
- 流媒体学习三-------SIP消息结构详解
SIP消息由三部分组成,即:开始行(start line).消息头(header).正文(body)Start-line:请求行Request-line 消息为 request消息时使用reques ...
- javascript 模式方面的学习
看了好多网上的文章,基本上得到一个结论:一些写类工具函数或框架的写类方式本质上都是 构造函数+原型 1.用构造函数来定义类属性(字段).2.用原型方式来定义类的方法. 具体文章请参阅 JavaScri ...
- dubbo的简单使用
整个过程大致是这样的 1.注册中心使用zookeeper,地址为192.168.192.128:2181! 2.首先服务方 所在的服务器是127.0.0.1:8081 服务方提供的接口: public ...
- Nested transactions in stored procedure of SQLServer
question: if the nested transaction encountered an exception, then rollbacked. How about the outer t ...