C# how to: write parallel using partition local variables Foreach loop

How to: write parallel. XML using partition local variables Foreach loop

The following example demonstrates how to write a that uses partition local variables ForEach Method. When ForEach When the loop executes, it divides its source collection into multiple partitions. Each partition has its own copy of the partition local variable. Partition local variables are similar to Thread local variable , but multiple partitions can run on a single thread.

The code and parameters in this example are very similar to the corresponding For Method. For more information, see How to: write parallel with thread local variables For loop.

To be in ForEach To use partitioned local variables in a loop, you must call one of the method overloads that takes two type parameters. The first type parameter , TSource , specifies the type of source element, and the second type parameter , TLocal , specifies the type of partition local variable.

Examples

The following example calls Parallel.ForEach<TSource,TLocal>(IEnumerable<TSource>, Func<TLocal>, Func<TSource,ParallelLoopState,TLocal,TLocal>, Action<TLocal>) Overloaded to calculate the sum of an array of one million elements. This overload has four parameters:

  • Source is the data source. It must be realized IEnumerable<T> . In our example, the data source is one million members returned by the {IEnumerable < int32 > method Enumerable.Range Object.

  • localInit, or a function that initializes partition local variables. Execute in it for each Parallel.ForEach The partition of the operation calls this function once. Our example initializes the partition local variable to zero.

  • body, which is called by the parallel loop for each iteration of the loop Func<T1,T2,T3,TResult> . Its signature is "func \ < tSource, parallelloopstate, tlocal, tlocal >. You provide code for the delegate, and the loop will pass in input parameters, which are:

    Your delegate returns a partition local variable and passes it to the next iteration of the loop executed in that particular partition. Each circular partition maintains a separate instance of this variable.

    In this example, the delegate adds the value of each integer to the partition local variable, which maintains the changing total number of integer element values in the partition.

  • localFinally, when the circular operation in each partition is completed, the action < tlocal > is called Parallel.ForEach Commission.   Parallel.ForEach Method passes the final value of the partition local variable of this circular partition to the action < tlocal > delegate, and you provide code to perform the actions required to merge the results from this partition with those from other partitions. This delegate can be invoked by multiple tasks in parallel. Therefore, this example uses Interlocked.Add(Int32, Int32) Method to synchronize access to the total variable. Because the delegate type is Action<T> Therefore, there is no return value.

C # replication

 using System;
 using System.Linq;
 using System.Threading;
 using System.Threading.Tasks;

 class Test
 {
     static void Main()
     {
         int[] nums = Enumerable.Range(0, 1000000).ToArray();
         long total = 0;

         // First type parameter is the type of the source elements
         // Second type parameter is the type of the thread-local variable (partition subtotal)
         Parallel.ForEach<int, long>(nums, // source collection
                                     () => 0, // method to initialize the local variable
                                     (j, loop, subtotal) => // method invoked by the loop on each iteration
                                     {
                                         subtotal += j; //modify local variable
                                         return subtotal; // value to be passed to next iteration
                                     },
             // Method to be executed when each partition has completed.
             // finalResult is the final value of subtotal for a particular partition.
                                     (finalResult) => Interlocked.Add(ref total, finalResult)
                                     );

         Console.WriteLine("The total from Parallel.ForEach is {0:N0}", total);
    }
}
// The example displays the following output:
//        The total from Parallel.ForEach is 499,999,500,000

Keywords: C# .NET

Added by fearfx on Fri, 11 Feb 2022 04:13:43 +0200