//-------------------------------------------------------------------------- // // Copyright (c) Microsoft Corporation. All rights reserved. // // File: ParallelAlgorithms_For.cs // //-------------------------------------------------------------------------- using System.Collections.Generic; using System.Numerics; using System.Threading.Tasks; namespace System.Threading.Algorithms { public static partial class ParallelAlgorithms { /// Executes a for loop in which iterations may run in parallel. /// The start index, inclusive. /// The end index, exclusive. /// The delegate that is invoked once per iteration. public static void For(BigInteger fromInclusive, BigInteger toExclusive, Action body) { For(fromInclusive, toExclusive, s_defaultParallelOptions, body); } /// Executes a for loop in which iterations may run in parallel. /// The start index, inclusive. /// The end index, exclusive. /// A System.Threading.Tasks.ParallelOptions instance that configures the behavior of this operation. /// The delegate that is invoked once per iteration. public static void For(BigInteger fromInclusive, BigInteger toExclusive, ParallelOptions options, Action body) { // Determine how many iterations to run... var range = toExclusive - fromInclusive; // ... and run them. if (range <= 0) { // If there's nothing to do, bail return; } // Fast path else if (range <= Int64.MaxValue) { // If the range is within the realm of Int64, we'll delegate to Parallel.For's Int64 overloads. // Iterate from 0 to range, and then call the user-provided body with the scaled-back value. Parallel.For(0, (long)range, options, i => body(i + fromInclusive)); } // Slower path else { // For a range larger than Int64.MaxValue, we'll rely on an enumerable of BigInteger. // We create a C# iterator that yields all of the BigInteger values in the requested range // and then ForEach over that range. Parallel.ForEach(Range(fromInclusive, toExclusive), options, body); } } /// Creates an enumerable that iterates the range [fromInclusive, toExclusive). /// The lower bound, inclusive. /// The upper bound, exclusive. /// The enumerable of the range. private static IEnumerable Range(BigInteger fromInclusive, BigInteger toExclusive) { for (var i = fromInclusive; i < toExclusive; i++) yield return i; } } }