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的更多相关文章

  1. .Net多线程编程—System.Threading.Tasks.Parallel

    System.Threading.Tasks.Parallel类提供了Parallel.Invoke,Parallel.For,Parallel.ForEach这三个静态方法. 1 Parallel. ...

  2. Java 8函数编程轻松入门(五)并行化(parallel)

    1.并发与并行的区别 并发: 一个时间段内有几个程序都处于已启动到运行完毕之间,且这几个程序都是在同一个处理机上运行.但在任一个时刻点只有一个程序在处理机上运行 并行: 在同一个时刻,多核处理多个任务 ...

  3. Parallel并行之乱用

    关于Parallel我也不细说了,一则微软封装的很好用,二来介绍这个的遍地都是. 我要说的是,要想成为一个优秀的标题党,一定要把重点放到别的地方,为了节省大家阅读时间,我先把结论说了,然后再慢慢从头说 ...

  4. 代码的坏味道(12)——平行继承体系(Parallel Inheritance Hierarchies)

    坏味道--平行继承体系(Parallel Inheritance Hierarchies) 平行继承体系(Parallel Inheritance Hierarchies) 其实是 霰弹式修改(Sho ...

  5. 多线程之任务: Task 基础, 多任务并行执行, 并行运算(Parallel)

    Task - 基于线程池的任务(在 System.Threading.Tasks 命名空间下) 多 Task 的并行执行 Parallel - 并行计算(在 System.Threading.Task ...

  6. Parallel.Foreach

    随着多核时代的到来,并行开发越来越展示出它的强大威力! 使用并行程序,充分的利用系统资源,提高程序的性能.在.net 4.0中,微软给我们提供了一个新的命名空间:System.Threading.Ta ...

  7. 在Parallel中使用DbSet.Add()发现的一系列多线程问题和解决过程

    发现问题 需求很简单,大致就是要批量往数据库写数据,于是打算用Parallel并行的方式写入,希望能利用计算机多核特性加快程序执行速度.想的很美好,于是快速撸了类似下面的一串代码: using (va ...

  8. Intel.parallel.studio.xe.2015.Update.2.ISO-TBE 下载

    磁力链下载点我 还有linux版本 Intel.parallel.studio.xe.2015.Update.1.LINUX.ISO-TBE 收集自网络,要跨请跨原作者,谢谢.

  9. Parallel并行编程初步

    Parallel并行编程可以让我们使用极致的使用CPU.并行编程与多线程编程不同,多线程编程无论怎样开启线程,也是在同一个CPU上切换时间片.而并行编程则是多CPU核心同时工作.耗时的CPU计算操作选 ...

  10. C#~异步编程再续~大叔所理解的并行编程(Task&Parallel)

    返回目录 并行这个概念出自.net4.5,它被封装在System.Threading.Tasks命名空间里,主要提供一些线程,异步的方法,或者说它是对之前Thread进行的二次封装,为的是让开发人员更 ...

随机推荐

  1. GIS空间分析案例教程——带背景和周围要素的逐要素导出地理

    GIS空间分析案例教程--带背景和周围要素的逐要素导出地理 商务合作,科技咨询,版权转让:向日葵,135-4855__4328,xiexiaokui#qq.com 目的:导出多边形要素类的每个要素 实 ...

  2. percona-mysql5.7.24使用xtrabackup工具配置主从同步

    主从配置详细过程: 环境准备: 配置好服务器,主从服务器都安装并启动mysql数据库 # 添加读写账号和只读账号,应用配置中,写主库用读写账号,统计从库数据yoga只读账号 grant select, ...

  3. Python3基础 内置函数 id

             Python : 3.7.3          OS : Ubuntu 18.04.2 LTS         IDE : pycharm-community-2019.1.3    ...

  4. 最简单的策略模式代替if-else实战

    一.需求 根据用户vip等级来返回不同的价格,vip等级是不固定的,随时可能要增加,价格也不是固定的. 二.常规的写法 /** * 如果有新增类型,就需要频繁的修改此处的代码! * 不符合开闭原则! ...

  5. keepalived+lvs tcp check 引起的后端服务报Connection reset by peer

    方法一: 取消LVS方式进行tcp转发,进而改为http方式反向代理,问题即可解决. 当然,这是在业务允许使用http的情况下,如果必须使用tcp协议,那就得使用下面的方法了. 方法二: 修改keep ...

  6. 【GStreamer开发】GStreamer播放教程03——pipeline的快捷访问

    目的 <GStreamer08--pipeline的快捷访问>展示了一个应用如何用appsrc和appsink这两个特殊的element在pipeline中手动输入/提取数据.playbi ...

  7. Andrew Ng机器学习课程9-补充

    Andrew Ng机器学习课程9-补充 首先要说的还是这个bias-variance trade off,一个hypothesis的generalization error是指的它在样本上的期望误差, ...

  8. JavaFX窗体设置无边框

    public void start(Stage stage) throws Exception { longStart(); Parent root = FXMLLoader.load(getClas ...

  9. eclipse设置格式化tab为4个空格和idea一样

  10. 热修复干货| AndFix热补丁动态修复框架使用教程

    本篇文章会与大家一起学习使用阿里的AndFix热修复框架,可以说AndFix是国内热修复技术的开山始祖,尽管现在阿里已经放弃了对这个项目的维护,但是后来很多的热修复技术都借鉴了这一框架的实现思路. 1 ...