【C#】61. 并行查询的异常处理 PLINQ Exception
来源:互联网 发布:霍华德新秀体测数据 编辑:程序博客网 时间:2024/05/01 05:38
本文主要是要说明PLINQ中如果发生了异常(除取消任务以外的异常),那么将会返回一个aggregateexception(因为所有并行查询中发生的异常都会被抛出),需要对其中的innerexception进行进一步处理。
首先来看普通Linq查询中发生的异常:由于是顺序执行查询,因此当碰到了对应的第一个异常时便自动捕获,也无须考虑线程的问题,因为是在同一个线程中。
IEnumerable<int> numbers = Enumerable.Range(-5, 10);var query = from number in numbers select 100 / number;try{foreach(var n in query) Console.WriteLine(n);}catch (DivideByZeroException){Console.WriteLine("Divided by zero!");}Console.WriteLine("---");Console.WriteLine("Sequential LINQ query processing");Console.WriteLine();
再来看一下并行查询的异常捕获:
var parallelQuery = from number in numbers.AsParallel()select 100 / number; ;try{parallelQuery.ForAll(Console.WriteLine);}catch (DivideByZeroException){Console.WriteLine("Divided by zero - usual exception handler!");}catch (AggregateException e){e.Flatten().Handle(ex =>{if (ex is DivideByZeroException){Console.WriteLine("Divided by zero - aggregate exception handler!");return true;}return false;});}Console.WriteLine("---");Console.WriteLine("Parallel LINQ query processing and results merging");
遇到这个异常时点击继续即可,无须理会。(原因是VS没有识别到下面我们写的异常处理代码)
可以看到,异常是被第二个catch所捕获,因此这是一个aggregateexception。
0 0
- 【C#】61. 并行查询的异常处理 PLINQ Exception
- Exception-异常处理(c++)的总结
- Objective-C - 异常处理(Exception)
- Objective-C - 异常处理(Exception)
- Objective-C - 异常处理(Exception)
- 并行编程(3):PLinq
- 并行开发3——plinq的使用
- 1.4.3.2 使用 PLINQ 的声明式并行
- C++------------------------>异常处理(Exception handling)
- 异常处理 Exception(C++Primer-11)
- C++、Java、JavaScript中的异常处理(Exception)
- 【C#】60. PLINQ 的几个选项
- C# 并行编程 之 PLINQ并行度的指定 和 ForAll的使用
- JAVA学习--异常Exception的处理
- Cpp的异常处理Exception Handling-笔记
- Exception-异常处理(java)的总结
- Exception:处理异常的两种方式
- Python中Exception的异常处理
- c# string类型和json之间的相互转换
- 如何在S函数中对变量或者输入信号进行求导
- Java中文件与目录管理
- 为指定目录的指定后缀文件首行添加“#coding:utf-8”
- 蓝鸥Unity入门Input类学习笔记
- 【C#】61. 并行查询的异常处理 PLINQ Exception
- Android基础总结+SQlite数据库【申明:来源于网络】
- windows下搭载tomcat运行环境
- Linux 常用命令
- ios 时区,时间格式NSDate
- Spark源码解析之小分区合并
- Ionic2 定义全局变量方法
- CDH安装指南
- Mysql对表格和表格中的字段添加注释