总结

总之,要编写一个健壮的并行循环,必须在并行循环体中检测 ParallelLoopState 对象的 IsExceptional, IsStopped 和 LowestBreakIteration 三个属性,出于简化编程的目的, ParallelLoopState 提供了一个 ShouldExitCurrentIteration 属性,当Stop()\cancel()时,ShouldExitCurrentIteration等于true。

方法 属性  
异常 IsExceptional ShouldExitCurrentIteration
Stop IsStopped ShouldExitCurrentIteration
Break LowestBreakIteration(循环索引起始是0)  

stop

可以多次被调用,对应的属性IsExceptional、IsStopped。当发生break后,IsStopped等于true,ShouldExitCurrentIteration等于true。

ParallelLoopResult plr= Parallel.For(1,20,(index, LoopState) =>{
if (i == 10)
{
// 当某一个循环单元的数==10,
// 则停止所有线程的Parallel.For的执行,已经执行循环执行完当前一轮循环后停止,未执行的循环直接停止执行。
LoopState.Stop();//执行Stop()LowestBreakIteration为空,Stop/Break互斥两个只能有一个执行,Stop停止循环比Break快。
  Console.WriteLine("ShouldExitCurrentIteration " + LoopState.ShouldExitCurrentIteration);//break 执行后ShouldExitCurrentIteration为true
 return;//不加return,可能会发生该进程资源未释放。
}
Console.WriteLine(index+ " ThreadId" + Environment.CurrentManagedThreadId); });
Console.WriteLine("LowestBreakIteration:" + plr.LowestBreakIteration);

break

可以多次被调用。对应的属性LowestBreakIteration、ShouldExitCurrentIteration。当发生break后,LowestBreakIteration等于最小那个index,ShouldExitCurrentIteration等于false

由于多线程执行,所以会有多个线程同时发生break,LowestBreakIteration取for循环最小那个index 。

ParallelLoopResult plr= Parallel.For(1,20,(index, LoopState) =>{
if (index == 10)
{
// 当某一个循环单元的数==10,
// 则首先停止当前 线程的Parallel.For的执行
//其他线程的For 满足条件则继续执行,直到满足条件或完成
// 所有执行单元结束后退出Parallel.For的执行
LoopState.Break();//LowestBreakIteration有值,Stop/Break互斥两个只能有一个执行,Stop停止循环比Break快。
 Console.WriteLine("ShouldExitCurrentIteration " + LoopState.ShouldExitCurrentIteration);//break 执行后对ShouldExitCurrentIteration为false 没影响

return;//不加return,可能会发生该进程资源未释放。 }
Console.WriteLine(index+ " ThreadId" + Environment.CurrentManagedThreadId);
});
Console.WriteLine("LowestBreakIteration:" + plr.LowestBreakIteration);

CancellationTokenSource 取消并行

namespace CancelParallelLoops
{
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks; class Program
{
static void Main()
{
int[] nums = Enumerable.Range(0, 10000000).ToArray();
CancellationTokenSource cts = new CancellationTokenSource(); // Use ParallelOptions instance to store the CancellationToken
ParallelOptions po = new ParallelOptions();
po.CancellationToken = cts.Token;
po.MaxDegreeOfParallelism = System.Environment.ProcessorCount;
Console.WriteLine("Press any key to start. Press 'c' to cancel.");
Console.ReadKey(); // Run a task so that we can cancel from another thread.
Task.Factory.StartNew(() =>
{
if (Console.ReadKey().KeyChar == 'c')
cts.Cancel();
Console.WriteLine("press any key to exit");
}); try
{
Parallel.ForEach(nums, po, (num) =>
{
double d = Math.Sqrt(num);
Console.WriteLine("{0} on {1}", d, Thread.CurrentThread.ManagedThreadId);
});
}
catch (OperationCanceledException e)
{
Console.WriteLine(e.Message);
}
finally
{
cts.Dispose();
} Console.ReadKey();
}
}
}

IsExceptional  属性(不知道如何使用)

ParallelLoopState 的 IsExceptional 属性为 true ,ShouldExitCurrentIteration等于true。

ShouldExitCurrentIteration 属性

总之,要编写一个健壮的并行循环,必须在并行循环体中检测 ParallelLoopState 对象的 IsExceptional, IsStopped 和 LowestBreakIteration 三个属性,出于简化编程的目的, ParallelLoopState 提供了一个 ShouldExitCurrentIteration 属性,当Stop()\cancel()时,ShouldExitCurrentIteration等于true。

Stop和Break

可以分别用来控制Parallel.For的执行。
Stop表示Parallel.For的执行立刻停止,无论其他执行单元是否达到停止的条件。

Break表示满足条件的当前执行单元立刻停止,而对于其他执行单元,其中满足停止条件也会通过Break停止,其他未满足停止条件的则会继续执行下去,从而全部执行完毕,自然停止。当所有执行单元停止后,Parallel.For函数才停止执行并退出。

执行Stop()LowestBreakIteration为空, LoopState.Break();LowestBreakIteration有值,Stop/Break互斥两个只能有一个执行,Stop停止循环比Break快。
break类似于for的continue,而stop就类似于for的break。

【C# Parallel】ParallelLoopState的更多相关文章

  1. 【C# Parallel】开端

    使用条件 1.必须熟练掌握锁.死锁.task的知识,他是建立这两个的基础上的.task建立在线程和线程池上的. 2.并不是所有代码都适合并行化. 例如,如果某个循环在每次迭代时只执行少量工作,或它在很 ...

  2. 【C# Parallel】ParallelOptions

    ParallelOptions 构造函数 此构造函数用默认值初始化实例. MaxDegreeOfParallelism 初始化为-1,表示没有对应采用的并行度进行上限设置. CancellationT ...

  3. 【知识点整理】Oracle中NOLOGGING、APPEND、ARCHIVE和PARALLEL下,REDO、UNDO和执行速度的比较

    [知识点整理]Oracle中NOLOGGING.APPEND.ARCHIVE和PARALLEL下,REDO.UNDO和执行速度的比较 1  BLOG文档结构图 2  前言部分 2.1  导读和注意事项 ...

  4. 【静默安装】configToolAllCommands响应文件问题

    [静默安装]configToolAllCommands响应文件问题 客户在静默安装RAC 12.1.0.2的时候有如下的输出: Successfully Setup Software. As inst ...

  5. 【Unity Shaders】学习笔记——渲染管线

    [Unity Shaders]学习笔记——Shader和渲染管线 转载请注明出处:http://www.cnblogs.com/-867259206/p/5595924.html 写作本系列文章时使用 ...

  6. 【exp/imp】将US7ASCII字符集的dmp文件导入到ZHS16GBK字符集的数据库中

    [exp/imp]将US7ASCII字符集的dmp文件导入到ZHS16GBK字符集的数据库中 1.1  BLOG文档结构图 1.2  前言部分 1.2.1  导读和注意事项 各位技术爱好者,看完本文后 ...

  7. 【新特性】JDK1.8

    一.简介 毫无疑问,Java 8是Java自Java 5(发布于2004年)之后的最重要的版本.这个版本包含语言.编译器.库.工具和JVM等方面的十多个新特性.在本文中我们将学习这些新特性,并用实际的 ...

  8. 【OCP|OCM】Oracle培训考证系列

     [OCP|OCM]Oracle培训考证系列  我的个人信息 网名:小麦苗 QQ:646634621 QQ群:618766405 我的博客:http://blog.itpub.net/26736162 ...

  9. 【大数据】Scala学习笔记

    第 1 章 scala的概述1 1.1 学习sdala的原因 1 1.2 Scala语言诞生小故事 1 1.3 Scala 和 Java  以及 jvm 的关系分析图 2 1.4 Scala语言的特点 ...

随机推荐

  1. 小程序或者vue,解决菜单导航做做成轮播的样子

    案例: 其中最重要的思路就是如何让第二次或第三次以及后面的轮播有数据: 做法大致跟轮播图做法一样,只不过我们需要进行书写样式,代码如下: <!-- 做一个轮播图navbar demo --> ...

  2. 使用XmlWriter写入XML

    麻了..整理完了发现XmlWriter不能添加元素,只能重写,还是得用Xdocument..好像DOM能实现添加元素 点击查看代码 **MemoryStream msXml = new MemoryS ...

  3. 计算机电子书 2019 BiliDrive 备份

    下载方式 pip install BiliDriveEx bdex download <link> 链接 文档 链接 传智播客轻松搞定系列 C.C++.Linux.设计模式.7z (33. ...

  4. 关于C++ scanf的一个小知识

    关于C++的scanf,其实在使用时有一个注意的点. 我们来看一个简单的例子. 对于输入的一行,如果这一行的开头需要输入一个字符,例如这样的输入: A 10 20 B 30 A 3 50 ... 我们 ...

  5. GC基础知识

    内存溢出和内存泄漏 内存溢出(Out Of Memory) 就是申请内存时,JVM没有足够的内存空间.通俗说法就是去蹲坑发现坑位满了. 内存泄露 (Memory Leak) 就是申请了内存,但是没有释 ...

  6. 总结一下Mac快捷键的图形符号

    Mac中主要有四个修饰键,分别是Command,Control,Option和Shift.这四个键分别有自己的图案,他们经常出现在Mac应用程序中的菜单栏里,方便你随时学习新的快捷键.

  7. SpringMVC主要组件

    1.DispatcherServlet:前端控制器,接收所有请求(如果配置/,则不包含jsp) 2.handlermapping:判断请求格式,判断希望具体要执行的那个方法 3.HanderAdapt ...

  8. shell——trap捕捉信号(附信号表)

    trap捕捉信号有三种形式 第一种:trap "commands" signal-list 当脚本收到signal-list清单内列出的信号时,trap命令执行双引号中的命令. 例 ...

  9. Hadoop启动错误——ERROR: Attempting to operate on hdfs namenode as root but there is no HDFS_NAMENODE_USER defined. Aborting operation.

    错误如下所示; [root@localhost sbin]# start-all.sh Starting namenodes on [192.168.71.129] ERROR: Attempting ...

  10. Spark算子 - reduce

    释义 reduce将partition内所有记录最终计算成1个记录,结果类型与reduce 时数据类型一致 方法签名如下: def reduce(f: (T, T) => T): T = wit ...