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进行的二次封装,为的是让开发人员更 ...
随机推荐
- elementUI 列表里面含有多选框,当翻页的时候依然保持之前页多选不变
el-table的type="selection"的使用 场景:el-table,type="selection"时,重新请求后,设置列表更新前的已勾选项 踩坑 ...
- TextFX Notepad++
textFx Notepad++ - 国内版 Bing https://cn.bing.com/search?FORM=U227DF&PC=U227&q=textFx+Notepad% ...
- Java基础 do-while 简单示例
JDK :OpenJDK-11 OS :CentOS 7.6.1810 IDE :Eclipse 2019‑03 typesetting :Markdown code ...
- git---分支的合并
git使用分支也可进行多人协作开发. 一.创建分支 git branch zhaozilong 创建一个 zhaozilong 的分支 二.查看所有的分支 git branch -a :查看当前的所有 ...
- Dart中的mixins
/* mixins的中文意思是混入,就是在类中混入其他功能. 在Dart中可以使用mixins实现类似多继承的功能,with关键字 因为mixins使用的条件,随着Dart版本一直在变,这里讲的是Da ...
- Linux系统调优——内核相关参数(五)
修改内核参数有3种办法:一种临时修改,两种永久修改. 临时修改是使用sysctl [选项] [参数名=值]命令:永久修改是修改/etc/sysctl.conf文件或修改/proc/sys/目录下的对应 ...
- LeetCode_299. Bulls and Cows
299. Bulls and Cows Easy You are playing the following Bulls and Cows game with your friend: You wri ...
- 【端口转发】k8s port-forward端口转发 和 ssh -NfL端口转发
kubectl port-forward端口转发 将远程pod端口转发到本地端口 kubectl port-forward monitoring-grafana-695c545f46-rhtwc -- ...
- sudo启动程序引发的进程个数不对
这几天把自己负责的服务改成了多进程模型,然后使用sudo来启动进程,示例程序如下: int main(void) { fork(); while(1); } 编译: `gcc ...
- web端自动化——自动化测试准备工作
准备工作# 在开始自己项目的自动化测试之前,我们最好已经完成了下面的准备工作: 1.熟悉待测系统 对项目的待测系统整体功能和业务逻辑有比较清晰的认识. 2.编写系统的自动化测试用例大纲和自动化测试用例 ...