Using the Ordered Default Partitioning Strategy

When you use the Parallel.ForEach() method, the default partitioning strategy will be applied unless the first argument you provide is an instance of the Partitioner or OrderablePartitioner classes in the System.Collections.Concurrent namespace. In the previous example, we applied the chunking strategy by creating an instance of OrderablePartitioner and passing it to Parallel.ForEach(). But now, it is time for me to admit that I fudged things slightly to make the example simpler.

The OrdereablePartitioner class extends Partitioner. When I called Parallel.ForEach() in the previous example, I used a version of the method that implicitly treated the argument as an instance of the base class, Partitioner. I did this because the feature that OrderablePartitioner adds over the base Partitioner doesn't have any relevance when chunking.

Any partitioner, be it implemented using Partitioner or OrderablePartitioner, is free to arrange the items in whatever order it wants to in each partition. This is fine when items are self-contained, such as Tuples representing index ranges. In such situations, you can use Partitioner either directly by extending the class or implicitly as I did in the previous example. But, if the data items have some kind of order, and you need to preserve that order, you need to use OrderablePartitioner instead. Listing 5-16 demonstrates the difference.

Listing 5-16. Using an Orderable Partitioner using System;

using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading.Tasks;

namespace Listing_l5 { class Listing_l5 {

static void Main(string[] args) {

// create the source data IList<string> sourceData

= new List<string>() { "an", "apple", "a", "day", "keeps", "the", "doctor", "away" };

// create an array to hold the results string[] resultData = new string[sourceData.Count];

// create an orderable partitioner

OrderablePartitioner<string> op = Partitioner.Create(sourceData);

// perform the parallel loop

0 0

Post a comment