简体   繁体   English

C#中的Spliterator等效项是什么?

[英]What is the equivalent of Spliterator in C#?

In Java I can write a Spliterator interface implementation, in which I can specify how exactly a source collection will be split into subcollections for parallel processing. 在Java中,我可以编写一个Spliterator接口实现,在其中可以指定将源集合精确地拆分为多个子集合以进行并行处理的方式。

But I don't understand how to do this in C#, all I know is that you can call AsParallel on IEnumerable , but can you control the splitting process? 但是我不明白如何在C#中执行此操作,我只知道可以在IEnumerable上调用AsParallel ,但是可以控制拆分过程吗?

For example, my source collection is an array and I want to split it into 5 item subarrays, and want linq to work with those subarrays. 例如,我的源集合是一个数组,我想将其拆分为5个项目子数组,并希望linq与这些子数组一起使用。 Is this possible? 这可能吗?

If you have specific partitioning requirements, you should have a look at Custom Partitioners for PLINQ and TPL and How to: Implement a Partitioner for Static Partitioning . 如果您有特定的分区要求,则应该查看PLINQ和TPL的自定义分区,以及如何:实现静态分区的分区 These give an example of how you can implement a Partitioner<TSource> , which is presumably similar to Java's Spliterator . 这些示例给出了如何实现Partitioner<TSource>的示例,该Partitioner<TSource>大概类似于Java的Spliterator

However, most of the time, it's more beneficial to let the framework pick its own dynamic partitioning strategy. 但是,在大多数情况下,让框架选择自己的动态分区策略会更有益。 If your requirement is to limit the level of concurrency to 5, you can use WithDegreeOfParallelism : 如果您的要求是将并发级别限制为5,则可以使用WithDegreeOfParallelism

var summary = ints
    .AsParallel()
    .WithDegreeOfParallelism(5)
    .Aggregate(
        seed: (
            count: 0,
            sum: 0,
            min: int.MaxValue,
            max: int.MinValue),
        updateAccumulatorFunc: (acc, x) => (
            count: acc.count + 1,
            sum: acc.sum + x,
            min: Math.Min(acc.min, x),
            max: Math.Max(acc.max, x)),
        combineAccumulatorsFunc: (acc1, acc2) => (
            count: acc1.count + acc2.count,
            sum: acc1.sum + acc2.sum,
            min: Math.Min(acc1.min, acc2.min),
            max: Math.Max(acc1.max, acc2.max)),
        resultSelector: acc => (
            acc.count,
            acc.sum,
            acc.min,
            acc.max,
            avg: (double)acc.sum / acc.count));

Currently C# dose not offer this feature like Java. 目前,C#无法像Java一样提供此功能。 Parallel tasks in C# have a MaxDegreeOfParallelism parameter which let you specify maximum number of concurrent tasks enabled by ParallelOptions instance and it automatically handle number of tasks. C#中的并行任务具有MaxDegreeOfParallelism参数,该参数可让您指定ParallelOptions实例启用的最大并发任务数,并自动处理任务数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM