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. python 设计模式之组合模式Composite Pattern

    #引入一 文件夹对我们来说很熟悉,文件夹里面可以包含文件夹,也可以包含文件. 那么文件夹是个容器,文件夹里面的文件夹也是个容器,文件夹里面的文件是对象. 这是一个树形结构 咱们生活工作中常用的一种结构 ...

  2. PostgreSQL 登录时在命令行中输入密码

    有时候需要设置定时任务直接执行 sql 语句,但是 postgresql 默认需要人工输入密码,以下命令可以直接在命令行中直接填入密码 PGPASSWORD=pass1234 psql -U MyUs ...

  3. PLSQL流函数代码 540页 【我】

    540页 流函数代码 -- Create table create table STOCKTABLE ( TICKER ), TRADE_DATE DATE, OPEN_PRICE NUMBER, C ...

  4. Python3入门(十三)——常用内置模块之时间日期模块datatime

    1.日期时间模块——datatime //其他模块例如time.calender等模块暂不展开 (1)获取当前时间:datatime.now(): from datetime import datet ...

  5. ros 学习 array 的添加

    array的添加,使用 arry[i]赋值时会出现段错误,需要使用array.push_back添加到数据中,在ros中array数组是以vector方式存储的. 例如: 包含数组的msg定义为: h ...

  6. Qt5.10使用了qml后打包发布应用遇到的问题

    现象: 按照https://www.cnblogs.com/judes/p/11247728.html的方法,能生成一些exe所需环境和动态库,但是打开程序,用到了qml的地方,全是黑色的. 原因: ...

  7. 【WebView】Android WebView中的Cookie操作

    Hybrid App(混合式应用)的开发过程中少不了与WebView的交互,在涉及到账户体系的产品中,包含了一种登录状态的传递.比如,在Native(原生)界面的登录操作,进入到Web界面时,涉及到账 ...

  8. Elasticsearch服务器开发(第2版).pdf 含目录

    Elasticsearch服务器开发(第2版) 介绍: <Elasticsearch服务器开发(第2版)>这一版针对Elasticsearch的新版本更新了内容,增加了第1版中遗漏的重要内 ...

  9. java使用Sonic 算法对音频变速不变声、变调、调整音量

    依赖库:https://github.com/waywardgeek/sonic 基础库:Sonic.java /* Sonic library Copyright 2010, 2011 Bill C ...

  10. Sequelize模型定义

    定义 定义模型与表之间的映射,使用 define 方法. Sequelize 会自动增加 createdAt 和 updated 属性,这样能知道一个实例的创建时间和最终修改时间.如果不想自动生成,可 ...