C#-Parallel
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks; namespace Try
{
public class ParallelTest
{
#region 分区块并行执行
public static void TestPartition()
{
var datas = Enumerable.Range(, ).ToList();
PartitionByPartCount(datas,);
PartitionByPartSize(datas,);
} private static void PartitionByPartCount<T>(IList<T> datas, int partCount)
{
var partSize = (int)Math.Ceiling(datas.Count / (double)partCount);
var partitioner = Partitioner.Create(, datas.Count, partSize);
Parallel.ForEach(partitioner, (part, state, partIndex) => {
for (int index = part.Item1; index < part.Item2; index++)
{
Console.WriteLine($"partIndex:{partIndex},index:{index},data:{datas[index]}");
}
});
} private static void PartitionByPartSize<T>(IList<T> datas, int partSize)
{
var partitioner = Partitioner.Create(, datas.Count, partSize);
Parallel.ForEach(partitioner, (part, state, partIndex) => {
for (int index = part.Item1; index < part.Item2; index++)
{
Console.WriteLine($"partIndex:{partIndex},index:{index},data:{datas[index]}");
}
});
}
#endregion #region 取消Parallel
public static void TestCancel()
{
int[] nums = Enumerable.Range(, ).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);
po.CancellationToken.ThrowIfCancellationRequested();
});
}
catch (OperationCanceledException e)
{
Console.WriteLine(e.Message);
}
finally
{
cts.Dispose();
} Console.ReadKey();
}
#endregion #region 异常处理
public static void TestException()
{
// Create some random data to process in parallel.
// There is a good probability this data will cause some exceptions to be thrown.
byte[] data = new byte[];
Random r = new Random();
r.NextBytes(data); try
{
ProcessDataInParallel(data);
}
catch (AggregateException ae)
{
var ignoredExceptions = new List<Exception>();
// This is where you can choose which exceptions to handle.
foreach (var ex in ae.Flatten().InnerExceptions)
{
if (ex is ArgumentException)
Console.WriteLine(ex.Message);
else
ignoredExceptions.Add(ex);
}
if (ignoredExceptions.Count > ) throw new AggregateException(ignoredExceptions);
} Console.WriteLine("Press any key to exit.");
Console.ReadKey();
} private static void ProcessDataInParallel(byte[] data)
{
// Use ConcurrentQueue to enable safe enqueueing from multiple threads.
var exceptions = new ConcurrentQueue<Exception>(); // Execute the complete loop and capture all exceptions.
Parallel.ForEach(data, d =>
{
try
{
// Cause a few exceptions, but not too many.
if (d < )
throw new ArgumentException($"Value is {d}. Value must be greater than or equal to 3.");
else
Console.Write(d + " ");
}
// Store the exception and continue with the loop.
catch (Exception e)
{
exceptions.Enqueue(e);
}
});
Console.WriteLine(); // Throw the exceptions here after the loop completes.
if (exceptions.Count > ) throw new AggregateException(exceptions);
}
#endregion
}
}
C#-Parallel的更多相关文章
- .Net多线程编程—System.Threading.Tasks.Parallel
System.Threading.Tasks.Parallel类提供了Parallel.Invoke,Parallel.For,Parallel.ForEach这三个静态方法. 1 Parallel. ...
- Java 8函数编程轻松入门(五)并行化(parallel)
1.并发与并行的区别 并发: 一个时间段内有几个程序都处于已启动到运行完毕之间,且这几个程序都是在同一个处理机上运行.但在任一个时刻点只有一个程序在处理机上运行 并行: 在同一个时刻,多核处理多个任务 ...
- Parallel并行之乱用
关于Parallel我也不细说了,一则微软封装的很好用,二来介绍这个的遍地都是. 我要说的是,要想成为一个优秀的标题党,一定要把重点放到别的地方,为了节省大家阅读时间,我先把结论说了,然后再慢慢从头说 ...
- 代码的坏味道(12)——平行继承体系(Parallel Inheritance Hierarchies)
坏味道--平行继承体系(Parallel Inheritance Hierarchies) 平行继承体系(Parallel Inheritance Hierarchies) 其实是 霰弹式修改(Sho ...
- 多线程之任务: Task 基础, 多任务并行执行, 并行运算(Parallel)
Task - 基于线程池的任务(在 System.Threading.Tasks 命名空间下) 多 Task 的并行执行 Parallel - 并行计算(在 System.Threading.Task ...
- Parallel.Foreach
随着多核时代的到来,并行开发越来越展示出它的强大威力! 使用并行程序,充分的利用系统资源,提高程序的性能.在.net 4.0中,微软给我们提供了一个新的命名空间:System.Threading.Ta ...
- 在Parallel中使用DbSet.Add()发现的一系列多线程问题和解决过程
发现问题 需求很简单,大致就是要批量往数据库写数据,于是打算用Parallel并行的方式写入,希望能利用计算机多核特性加快程序执行速度.想的很美好,于是快速撸了类似下面的一串代码: using (va ...
- Intel.parallel.studio.xe.2015.Update.2.ISO-TBE 下载
磁力链下载点我 还有linux版本 Intel.parallel.studio.xe.2015.Update.1.LINUX.ISO-TBE 收集自网络,要跨请跨原作者,谢谢.
- Parallel并行编程初步
Parallel并行编程可以让我们使用极致的使用CPU.并行编程与多线程编程不同,多线程编程无论怎样开启线程,也是在同一个CPU上切换时间片.而并行编程则是多CPU核心同时工作.耗时的CPU计算操作选 ...
- C#~异步编程再续~大叔所理解的并行编程(Task&Parallel)
返回目录 并行这个概念出自.net4.5,它被封装在System.Threading.Tasks命名空间里,主要提供一些线程,异步的方法,或者说它是对之前Thread进行的二次封装,为的是让开发人员更 ...
随机推荐
- layui 鼠标悬停单元格显示全部
{field : 'subjectId',title : '主题id',align: 'center',edit : 'text',templet:'<div><span title ...
- Centos7迁移fastdfs文件系统
系统从一个地方迁移到另一个地方,数据保持不变,但是ip地址和网络情况不一样了,最困难的是要迁移的那个地方还么有互联网,这TM就坑了,所以想到将FastDFS存储的目录整体拷贝过去,这个方法简单粗暴,这 ...
- HDCMS多图字段的使用?
下面是HDCMS多图字段的简单使用: HDCMS在后台添加的多图,存到数据的时候是经过序列化过的,所以在使用的时候需要进行反序列化操作: $moreImg = M('keshi')->where ...
- java8 数据集过滤removeIf和filter
对象如下,需求:只要30岁以下的人 //求职者的实体类 public class Person { private String name;//姓名 private Integer age;//年龄 ...
- 【Dart学习】--Dart之数字(num)相关方法总结
一,部分属性 用法一(figureA) int figureA = -93; 是否为负数 print(figureA.isNegative); figureA是否是有限的 print(figureA. ...
- 改进初学者的PID-介绍
最近看到了Brett Beauregard发表的有关PID的系列文章,感觉对于理解PID算法很有帮助,于是将系列文章翻译过来!在自我提高的过程中,也希望对同道中人有所帮助.作者Brett Beaure ...
- 转Python 爬虫入门实战
转自:https://www.cnblogs.com/babycomeon/p/11651888.html
- jenkins编译时文件存放的位置
1.首先随便打包编译一下 2.查看编译执行的目录 [root@bogon ~]# ls /root/.jenkins/workspace/pipline-test/ CHANGE_LOGS.html ...
- 【CSS3 DEMO】扑克正反面翻牌效果
在线预览地址:http://dtdxrk.github.io/game/css3-demo/drawbox.html 用到两个属性: 一个是动画时间 transition-duration: 0.8s ...
- Spring Boot 初学避免犯不必要的错误
创建项目时的目录问题: 新包体(例如controller)必须和启动文件 DemoApplication.java 在同一级目录下,如下 spring boot 初步使用创建新的项目:https:// ...