C # Parallel tasks-Parallel class,

Source: Internet
Author: User

C # Parallel tasks-Parallel class,

1. Parallel class

The Parallel class provides data and task concurrency;

Ii. Paraller. ()

The Paraller. For () method is similar to the for loop Statement of C # and is used to execute a task multiple times. The Paraller. For () method can be used For parallel iteration. The iteration sequence is not defined.

In the For () method, the first two parameters are fixed, which define the beginning and end of the loop. First, describe its first method For (int, int, Action <int>). The first two parameters represent the beginning and introduction of the loop, and the third parameter is a delegate, an integer is the number of iterations of a loop. this parameter is passed to the delegate reference method. Paraller. the return type of the For () method is the ParallelLoopResult structure, which provides information about whether the loop ends and the index of the lowest iteration (returns an integer representing the lowest iteration from which the Break statement is called ). First, write an example:

ParallelLoopResult result = Parallel. for (0, 10, I => {Console. writeLine ("iterations: {0}, Task ID: {1}, thread ID: {2}", I, Task. currentId, Thread. currentThread. managedThreadId); Thread. sleep (10) ;}); Console. writeLine ("completed: {0}", result. isCompleted); Console. writeLine ("minimum iteration: {0}", result. lowestBreakIteration );

The output result is as follows:

As you can see, this delegate method runs 10 times, and the order is not guaranteed. However, the minimum iteration does not produce data because it is the integer that returns the minimum iteration that calls the Break statement. Here we do not have a break. If you need to interrupt the For () method in advance during execution, you can use ParallelLoopState For (int, int, Action <int, ParallelLoopState> ). Modify the preceding example:

ParallelLoopResult result = Parallel. for (0, 10, (I, state) => {Console. writeLine ("iterations: {0}, Task ID: {1}, thread ID: {2}", I, Task. currentId, Thread. currentThread. managedThreadId); Thread. sleep (10); if (I> 5) state. break () ;}); Console. writeLine ("completed: {0}", result. isCompleted); Console. writeLine ("minimum iteration: {0}", result. lowestBreakIteration );

The output result is as follows:

Iii. Parallel. ForEach ()

The Paraller. ForEach () method implements the IEnumerable set. Its method is similar to the foreach statement, but it is traversed asynchronously. The traversal order is not determined here. First, describe its first method, Paraller. ForEach <TSource> (IEnumerable <TSource>, Action <TSource>). First, let's look at the following example;

String [] data = {"str1", "str2", "str3"}; ParallelLoopResult result = Parallel. forEach <string> (data, str => {Console. writeLine (str) ;}); Console. writeLine ("completed: {0}", result. isCompleted); Console. writeLine ("minimum iteration: {0}", result. lowestBreakIteration );

The output result is as follows:

It can also pass in the number of iterations and ParallelLoopState like For by means of ForEach <TSource> (IEnumerable <TSource> source, Action <TSource, ParallelLoopState, long> body ), next, modify the preceding example.

String [] data = {"str1", "str2", "str3", "str4", "str5"}; ParallelLoopResult result = Parallel. forEach <string> (data, (str, state, I) => {Console. writeLine ("iterations: {0}, {1}", I, str); if (I> 3) state. break () ;}); Console. writeLine ("completed: {0}", result. isCompleted); Console. writeLine ("minimum iteration: {0}", result. lowestBreakIteration );

The output result is as follows:

4. Parallel. Invoke ()

Parallel. Invoke () method, which provides the task concurrency mode. The Paraller. Invoke () method allows you to pass an array of Action delegates, where you can specify the method to be run. See the following example.

            Parallel.Invoke(() =>            {                Thread.Sleep(100);                Console.WriteLine("method1");            }, () =>            {                Thread.Sleep(10);                Console.WriteLine("method2");            });

The output result is as follows:

V. Conclusion

The Parallel. For () and Paraller. ForEach () Methods call the same code in each iteration, while the Parallel. Invoke () method allows different methods to be called at the same time. Parallel. ForEach () is used for data concurrency, and Parallel. Invoke () is used for task concurrency;

 

 

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.