1 //--------------------------------------------------------------------------
3 // Copyright (c) Microsoft Corporation. All rights reserved.
5 // File: ParallelAlgorithms_SpeculativeFor.cs
7 //--------------------------------------------------------------------------
9 using System.Collections.Generic;
10 using System.Threading.Tasks;
12 namespace System.Threading.Algorithms
14 public static partial class ParallelAlgorithms
16 /// <summary>Executes a function for each value in a range, returning the first result achieved and ceasing execution.</summary>
17 /// <typeparam name="TResult">The type of the data returned.</typeparam>
18 /// <param name="fromInclusive">The start of the range, inclusive.</param>
19 /// <param name="toExclusive">The end of the range, exclusive.</param>
20 /// <param name="options">The options to use for processing the loop.</param>
21 /// <param name="body">The function to execute for each element.</param>
22 /// <returns>The result computed.</returns>
23 public static TResult SpeculativeFor<TResult>(
24 int fromInclusive, int toExclusive, Func<int, TResult> body)
26 return SpeculativeFor(fromInclusive, toExclusive, s_defaultParallelOptions, body);
29 /// <summary>Executes a function for each value in a range, returning the first result achieved and ceasing execution.</summary>
30 /// <typeparam name="TResult">The type of the data returned.</typeparam>
31 /// <param name="fromInclusive">The start of the range, inclusive.</param>
32 /// <param name="toExclusive">The end of the range, exclusive.</param>
33 /// <param name="options">The options to use for processing the loop.</param>
34 /// <param name="body">The function to execute for each element.</param>
35 /// <returns>The result computed.</returns>
36 public static TResult SpeculativeFor<TResult>(
37 int fromInclusive, int toExclusive, ParallelOptions options, Func<int, TResult> body)
39 // Validate parameters; the Parallel.For we delegate to will validate the rest
40 if (body == null) throw new ArgumentNullException("body");
42 // Store one result. We box it if it's a value type to avoid torn writes and enable
43 // CompareExchange even for value types.
46 // Run all bodies in parallel, stopping as soon as one has completed.
47 Parallel.For(fromInclusive, toExclusive, options, (i, loopState) =>
49 // Run an iteration. When it completes, store (box)
50 // the result, and cancel the rest
51 Interlocked.CompareExchange(ref result, (object)body(i), null);
55 // Return the computed result
56 return (TResult)result;