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
}
}

最新文章

  1. CSS3鼠标滑过图标放大以及旋转
  2. iOS - 如何切图适配各种机型
  3. python之网络编程
  4. Java:回调机制
  5. XBOX ONE游戏开发之登陆服务器(一)
  6. webdriver中定位元素,报无法找到元素的问题
  7. 学习日记day8:移动端页面流程优化
  8. centos JDK安装
  9. SNMP 和 NetBios协议理解
  10. C# File
  11. dubbo-RPC学习(一)自定义配置
  12. 解决配置android开发环境eclipse获取ADT获取不到,一直&quot;Pending&quot;
  13. MySQL 加密/压缩函数
  14. Openjudge-计算概论(A)-短信计费
  15. JAVA基本数据类型和引用数据类型的区别
  16. 内核调试神器SystemTap — 简介与使用(一)
  17. Shell命令-文件及目录操作之chattr、lsattr
  18. swiper常见问题
  19. Kivy中文编程指南--https://cycleuser.gitbooks.io/kivy-guide-chinese/content/
  20. 洛谷P1414又是毕业季二题解

热门文章

  1. [原][osg][OSGEARTH]OE的关闭打开自动计算裁剪面被OE的海洋ocean影响
  2. 004-guava 集合-新增集合类型-MultiSet, MultiMap, BiMap , Table, ClassToInstanceMap, RangeSe, RangeMap等
  3. Spring cloud微服务安全实战-4-5搭建OAuth2认证服务器
  4. Spring MVC 数据转换和格式化
  5. Pythonrandom模块(获取随机数)常用方法和使用例子
  6. Spring4.X整合redis
  7. LODOP插件的IE浏览器的安全设置
  8. js中的eval方法
  9. Java基础教程:多线程杂谈——双重检查锁与Volatile
  10. nodejs中利用expresss脚手架和bootstrap,数据库mongodb搭建的留言板案例