Parallel. For a very practical overload method that you may ignore, the parallel. for overload

Source: Internet
Author: User

Parallel. For a very practical overload method that you may ignore, the parallel. for overload

Speaking of Parallel. For, everyone is familiar with it. It's very simple. Isn't it a for loop that provides Parallel functions? You may usually use the simplest overload method.

There are 14 overload methods in Parallel. For, and some of the complicated overload methods may not know how to use them ~~~ I recently have an application scenario. I would like to introduce it to you,

Let's take a look at the reload list of this parallel method...

 

I. Scenarios

I encountered this scenario. The project has such a function. This function needs to filter a group of mermeridlists based on multiple dimensions, and finally obtain the Union of customers from multiple dimensions, let me give you an example.

Example: eight existing dimensions:

1. Transaction Behavior

2. marketing activities

3. Region

4. new and old customers

5. Marketing channels

6. customer attributes

7. Customer Group

8. Goods

Each dimension can filter out a batch of mermerids and then calculate the Union set for the eight groups of mermerids. To improve performance, you must perform parallel processing, of course, there are many ways to achieve this,

For example, if I define 8 tasks <T>, use WaitAll to wait, and accumulate the results of each Result, the Code is as follows:

1 class Program 2 {3 static void Main (string [] args) 4 {5 List <string> rankList = Enum. getNames (typeof (FilterType )). toList (); 6 7 Task <HashSet <int> [] tasks = new Task <HashSet <int> [rankList. count]; 8 9 var hashhashmeridlist = new HashSet <int> (); // calculate the Union of mermerid 10 11 for (int I = 0; I <tasks. length; I ++) 12 {13 tasks [I] = Task. factory. startNew <HashSet <int> (obj) => 14 {15 // business method, consumption loss performance... 16 var smallCustomerIDHash = GetXXXMethod (rankList [(int) obj]); 17 18 return smallCustomerIDHash; 19}, I); 20} 21 22 Task. waitAll (tasks); 23 24 foreach (var task in tasks) 25 {26 foreach (var item in task. result) 27 {28 hashCustomerIDList. add (item); 29} 30} 31} 32 33 static HashSet <int> GetXXXMethod (string rank) 34 {35 return new HashSet <int> (); 36} 37 38 public enum FilterType39 {40 transaction behavior = 12848 marketing activities = region = new and old customers = marketing channels = 16, 45 customer attributes = 32, 46 customer groups = 64, 47 goods =} 49}

The logic of the above Code is still very simple. I use the Task <T> mode. Of course, you can also use a Task in the form of void, and then perform hashCustomerIDList during code lock.

Insertion is also very simple to implement. I will not demonstrate it. The following question comes: is there a better and more direct way to see how people look better, what about this effect?

 

Ii. Parallel. For complex Overloading

Back to the topic at the beginning of the article, first of all, we will carefully analyze the complex overload method under the remark.

1 // 2 // Summary: 3 // execute a for (For in Visual Basic) loop with local thread data, which may run iterations in parallel, it can also monitor the status of the operation cycle. 4 // 5 // parameter: 6 // fromInclusive: 7 // start index (inclusive ). 8 // 9 // toExclusive: 10 // end index (not included ). 11 // 12 // localInit: 13 // function delegate used to return the initial state of local data for each task. 14 // 15 // body: 16 // delegates will be called once for each iteration. 17 // 18 // localFinally: 19 // delegate for performing a final operation on the local status of each task. 20 // 21 // type parameter: 22 // TLocal: 23 // type of the local data of the thread. 24 // 25 // return result: 26 // structure containing information about completed Loops. 27 // 28 // exception: 29 // T: System. ArgumentNullException: 30 // The body parameter is null. -Or-The localInit parameter is null. -Or-The localFinally parameter is null. 31 // 32 // T: System. aggresponexception: 33 // contains all single exceptions thrown on all threads. 34 public static ParallelLoopResult For <TLocal> (int fromInclusive, int toExclusive, Func <TLocal> localInit, Func <int, ParallelLoopState, TLocal, TLocal> body, Action <TLocal> localFinally );

 

From the code area above, you can see that the above five parameters are provided, and the last meaning is the next three. If you are familiar with the extension method of linq, you will find that this is actually a parallel version.

Because they all have three regions: the first region is the initial region (localInit), which is an initialization operation before the accumulation, and the second region is actually an iteration.

Area. To put it bluntly, it is the foreach/for loop. In the for loop, the calculation result is accumulated to the variable set in the initial region, the Third Region is a final computing zone after foreach/.

This is a parallel accumulator. To help you better understand it, I will take a look at the source code:

 

Because the figure is too large, we will take two screenshots. You must carefully understand the tlocal variable, because the use of this tlocal variable runs through three regions, therefore, you must understand the following code.

1 TLocal tLocal = default(TLocal);2 3 tLocal = localInit();4 5 while(xxx<xxx){6 tLocal = bodyWithLocal(num5, parallelLoopState, tLocal);7 }8 localFinally(tLocal);

 

After you understand that tLocal has the result of accumulating items in foreach, you should understand the following body => (item, loop, total) and finally => (total) total in,

Right, when you understand it, then you can look at the following code. Is it possible to use a method to solve a business logic that originally needs to be implemented in stages?

1 class Program 2 {3 static void Main (string [] args) 4 {5 List <string> rankList = Enum. getNames (typeof (FilterType )). toList (); 6 7 var hashhashmeridlist = new HashSet <int> (); // calculate the Union of customerid 8 9 // calculate the total of seven dimensions in Parallel 10 Parallel. for (0, rankList. count, () =>{ return new List <int> () ;}, (item, loop, total) => 11 {12 // business method,... 13 var smallCustomerIDHash = GetXXXMethod (rankList [item]); 14 15 total. addRange (smallCustomerIDHash); 16 17 return total; 18}, (total) => 19 {20 lock (hashCustomerIDList) 21 {22 foreach (var customerID in total) 23 {24 hashCustomerIDList. add (customerID); 25} 26} 27}); 28} 29 30 static HashSet <int> GetXXXMethod (string rank) 31 {32 return new HashSet <int> (); 33} 34 35 public enum FilterType36 {37 transaction behavior = 12845 marketing activities = region = new and old customers = marketing channels = 16, 42 customer attributes = 32, 43 customer groups = 64, 44 goods =} 46}

Okay, so I will talk about this in this article. I hope this Parallel. For with the effect of Parallel accumulators will bring you a little inspiration ~~~

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.