C# 任务的异常和延续处理

写在前面

当Task在执行过程中出现异常或被取消等例外的情况时,为了让执行流程能够继续进行,可以使用延续方法实现这种链式处理;还可以针对前置任务不同的执行结果,选择执行不同的延续分支方法。子任务执行过程中的任何异常都会被传递到延续方法中进行统一处理,因此而增强了对并行任务的流程控制。

代码实现

cs 复制代码
        public static void ContinueWithException()
        {
            TaskCreationOptions tco = TaskCreationOptions.AttachedToParent;
            Task task = Task.Factory.StartNew(() =>
            {
                Task.Factory.StartNew(() => { throw new Exception(Environment.NewLine + "first exception" + Environment.NewLine); }, tco);
                Task.Factory.StartNew(() => { throw new Exception(Environment.NewLine + "second exception" + Environment.NewLine); }, tco);
                Task.Factory.StartNew(() => { throw new Exception(Environment.NewLine + "third exception" + Environment.NewLine); }, tco);
            }).ContinueWith(t => Console.WriteLine("Message:" + t.Exception.Message + Environment.NewLine), TaskContinuationOptions.OnlyOnFaulted);
            task.Wait();


            Task task01 = Task.Factory.StartNew(() =>
            {
                Console.WriteLine("task01 executed.");
            });
            Task ok1 = task01.ContinueWith(t => Console.WriteLine("Ok"), TaskContinuationOptions.NotOnFaulted);
            Task fail1 = task01.ContinueWith(t => Console.WriteLine("Failure:" + t.Exception.Message), TaskContinuationOptions.OnlyOnFaulted);

            Task task02 = Task.Factory.StartNew(() =>
            {
                throw new Exception("task02 executed.");
            });
            Task ok2 = task02.ContinueWith(t => Console.WriteLine("Ok"), TaskContinuationOptions.NotOnFaulted);
            Task fail2 = task02.ContinueWith(t => Console.WriteLine("Failure:" + t.Exception.Message), TaskContinuationOptions.OnlyOnFaulted);

        }

调用结果

如图,子任务中分别抛出的三个异常信息都被传递到了延续方法中,程序依然可以继续执行;另外task01和task02分别根据执行情况进入了不同的延续分支方法。

相关推荐
枫叶丹427 分钟前
【Qt开发】多元素类控件(三)-> QTreeWidget
开发语言·数据库·c++·qt
晨非辰31 分钟前
【数据结构入坑指南】--《层序分明:堆的实现、排序与TOP-K问题一站式攻克(源码实战)》
c语言·开发语言·数据结构·算法·面试
洲覆41 分钟前
Redis 驱动适配 Reactor 模式
开发语言·网络·数据库·redis
fl17683141 分钟前
基于matlab实现的DnCNN网络
开发语言·matlab
第二层皮-合肥42 分钟前
如何设置等长的最大走线长度
服务器·开发语言·php
掘根1 小时前
【Protobuf】proto3语法详解1
开发语言·前端·javascript
Lee_yayayayaya1 小时前
《通信之道—从微积分到5G》阅读笔记
开发语言·matlab
普密斯科技1 小时前
图像尺寸测量仪应用Type-C接口:精准检测,赋能科技
c语言·开发语言·科技
虚行1 小时前
C#技术栈
开发语言·c#
唐青枫2 小时前
C#.NET SqlKata 使用详解:优雅构建动态 SQL 查询
c#·.net