从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抛出异常后怎么取消其他线程的更多相关文章

  1. 转载 .Net多线程编程—任务Task https://www.cnblogs.com/hdwgxz/p/6258014.html

    .Net多线程编程—任务Task   1 System.Threading.Tasks.Task简介 一个Task表示一个异步操作,Task的创建和执行是独立的. 只读属性: 返回值 名称 说明 ob ...

  2. .Net多线程编程—任务Task

    1 System.Threading.Tasks.Task简介 一个Task表示一个异步操作,Task的创建和执行是独立的. 只读属性: 返回值 名称 说明 object AsyncState 表示在 ...

  3. java并发编程实战:第七章----取消与关闭

    Java没有提供任何机制来安全地终止线程(虽然Thread.stop和suspend方法提供了这样的机制,但由于存在缺陷,因此应该避免使用 中断:一种协作机制,能够使一个线程终止另一个线程的当前工作 ...

  4. 一个 Task 不够,又来一个 ValueTask ,真的学懵了!

    一:背景 1. 讲故事 前几天在项目中用 MemoryStream 的时候意外发现 ReadAsync 方法多了一个返回 ValueTask 的重载,真是日了狗了,一个 Task 已经够学了,又来一个 ...

  5. C#并发编程-2 异步编程基础-Task

    一 异步延迟 在异步方法中,如果需要让程序延迟等待一会后,继续往下执行,应使用Task.Delay()方法. //创建一个在指定的毫秒数后完成的任务. public static Task Delay ...

  6. .NET 中 如果一个Task A正在await另一个Task B,那么Task A是什么状态

    新建一个.NET Core控制台程序,输入如下代码: using System; using System.Threading; using System.Threading.Tasks; class ...

  7. c# 写着玩的,两个Task并发,一个写队列一个读队列的异常情况

    class Program { class TestEnqueue { static Queue<string> str = new Queue<string>(); publ ...

  8. 临远大神,你为啥要建立一个 TASK表。HumanTaskDTO

    临远大神,你为啥要建立一个 TASK表.HumanTaskDTO HumanTask这张表的作用是什么. 为了实现理想中的任务中心.TaskCenter. 首先,工作流可能会完全不包含任何人工节点,全 ...

  9. 【C# Task】 ValueTask/Task<TResult>

    概要 1.如果异步方法的使用者使用 Task.WhenAll 或 Task.WhenAny,则在异步方法中使用 ValueTask<T> 作为返回类型可能会产生高昂的成本.这是因为您需要使 ...

随机推荐

  1. [SHELL进阶] (转)最牛B的 Linux Shell 命令 (三)

    1. 更友好的显示当前挂载的文件系统 mount | column -t 这条命令适用于任何文件系统,column 用于把输出结果进行列表格式化操作,这里最主要的目的是让大家熟悉一下 columnt ...

  2. Bootstrap页面布局5 - 响应式布局(格式)

    旨在优化不同上网设备中页面显示的优化 响应式布局:就是根据浏览窗口的尺寸,改变页面的变化 原理:利用css的media-queries判断浏览窗口的尺寸,在CSS样式表中设置一些规则! 例如: 在&l ...

  3. 蓝牙BLE LINK LAYER剖析(一) -- status and channel

    一.LINK LAYER STATES 二.PHYSICAL CHANNEL

  4. nRF51822之app_button控制uart的开启和关闭

    为什么要使用app_button来控制uart的开启和关闭 还是先上datesheet中uart开启的时候需要HFCLK,需要消耗大量大电流.所以在我们需要的时候需要通过io来通知nrf51822开启 ...

  5. HBase的属性

    一:基本属性 1.查看属性 2.解释属性 NAME:列簇名 BLOOMFILTER:布隆过滤器,用于对storefile的过滤 共有三种类型: ROW:行健过滤 ROWCOL:行列过滤 NONE:无 ...

  6. 自己写的一个DirectUI库,基础控件基本都已实现

    http://download.csdn.net/detail/pcradio/9254881 http://blog.csdn.net/pcradio

  7. java System.out

    从写Hello World开始,我们就开始使用System.out了.System.out是一个static final 的PrintStream对象. 引用一段jdk API document的内容 ...

  8. SQL集合函数中利用case when then 技巧

    我们都知道SQL中适用case when then来转化数据库中的信息 比如  select (case sex when 0 then '男' else '女' end) AS sex  from ...

  9. node.js创建服务器报错

    创建nodeTest.js如下: var http = require('http'); http.createServer(function (request, response){ respons ...

  10. 分布式服务框架dubbo原理解析 转

    alibaba有好几个分布式框架,主要有:进行远程调用(类似于RMI的这种远程调用)的(dubbo.hsf),jms消息服务(napoli.notify),KV数据库(tair)等.这个框架/工具/产 ...