【C#】60. PLINQ 的几个选项

本篇主要介绍在使用并行查询时的几个选项,包括指定并行度(WithDegreeOfParallelism)、是否强制使用并行执行模式(WithExecutionMode)、对于查询结果的合并选项(WithMergeOptions)以及取消选项(WithCancellation)。

static IEnumerable GetTypes()
{
return from assembly in AppDomain.CurrentDomain.GetAssemblies()
from type in assembly.GetExportedTypes()
where type.Name.StartsWith("Web")
orderby type.Name.Length
select type.Name;
}
static string EmulateProcessing(string typeName)
{
Thread.Sleep(TimeSpan.FromMilliseconds(new Random(DateTime.Now.Millisecond).Next(250,350)));
Console.WriteLine("{0} type was processed on a thread id {1}",typeName, Thread.CurrentThread.ManagedThreadId);
return typeName;
}


示例函数:

var parallelQuery = from t in GetTypes().AsParallel() select EmulateProcessing(t);

var cts = new CancellationTokenSource();
cts.CancelAfter(2000);

try
{
parallelQuery
.WithDegreeOfParallelism(Environment.ProcessorCount)
.WithExecutionMode(ParallelExecutionMode.ForceParallelism)
.WithMergeOptions(ParallelMergeOptions.Default)
.WithCancellation(cts.Token)
.ForAll(Console.WriteLine);
}
catch (OperationCanceledException)
{
Console.WriteLine("---");
Console.WriteLine("Operation has been canceled!");
}
【C#】60. PLINQ 的几个选项_第1张图片

简单说明一下:示例函数中构造了AsParallel并行查询语句parallelQuery。对于该对象,先设置了他的最大并行度为运行机器的处理器数量,执行模式为强制使用并行查询(因为PLINQ会自动判断是否有必要使用并行查询),结果合并选项使用的是默认值(PLINQ会在查询返回结果前缓存一定数量的结果, 如果查询花费了大量的时间,那么应当关闭结果缓存从而尽可能快地得到结果),最后是取消选项,其中传入参数cts.Token 。由于cts.CancelAfter(1000),因此一秒钟后将取消查询,同时发出异常,被try catch模块捕获并处理(同步上下文?)。

你可能感兴趣的:(【C#】60. PLINQ 的几个选项)