Examples of parallel classes for C # parallel tasks

Source: Internet
Author: User
First, parallel class

The parallel class provides the parallelism of data and tasks;

Second, paraller.for ()

The Paraller.for () method is similar to the FOR Loop statement for C #, and it is a task that executes multiple times. Using the Paraller.for () method, iterations can be run in parallel, and the order of the iterations is undefined.

In the For () method, the first two parameters are fixed, and the two parameters define the start and end of the loop. First describes its first method for (int,int,action<int>), the preceding two parameters represent the beginning and the introduction of the loop, the third parameter is a delegate, the integer parameter is the number of iterations of the loop, and the argument is passed to the delegate reference method. The return type of the Paraller.for () method is the Parallelloopresult structure, which provides information about whether the loop ends and the index of the lowest iteration (returns an integer that represents the lowest iteration from which the break statement was called). Let's write an example:

            Parallelloopresult result = Parallel.For (0, ten, I =>{                Console.WriteLine ("Iteration count: {0}, Task Id:{1}, Thread id:{2}", I, Task.currentid, Thread.CurrentThread.ManagedThreadId);                Thread.Sleep (ten);            });            Console.WriteLine ("Whether complete: {0}", result.) iscompleted);            Console.WriteLine ("Minimum iteration: {0}", result.) Lowestbreakiteration);

The output results are as follows:

As you can see, the delegate method runs 10 times, and the order is not guaranteed. But the lowest iteration has no data, because he is the integer that returns the lowest iteration of the break statement, where we do not break. If you need to interrupt the for () method prematurely during execution, you can use ParallelLoopState to implement, for (int,int,action<int,parallelloopstate>). Change the example above:

            Parallelloopresult result = Parallel.For (0, ten, (I, State) =>{                Console.WriteLine ("Number of iterations: {0}, Task Id:{1}, Thread id:{2}", I, Task.currentid, Thread.CurrentThread.ManagedThreadId);                Thread.Sleep, if (i > 5) State                    . Break ();            });            Console.WriteLine ("Whether complete: {0}", result.) iscompleted);            Console.WriteLine ("Minimum iteration: {0}", result.) Lowestbreakiteration);

The output results are as follows:

Third, Parallel.ForEach ()

The Paraller.foreach () method traversal implements the collection of IEnumerable, which is similar to the ForEach statement, but traverses asynchronously, and there is no determination of the traversal order. First describe its first method,paraller.foreach<tsource> (ienumerable<tsource>,action<tsource>), first look at the following example;

            string[] data = {"Str1", "str2", "STR3"};            Parallelloopresult result = parallel.foreach<string> (data, str = = =                  Console.WriteLine (str);              });            Console.WriteLine ("Whether complete: {0}", result.) iscompleted);            Console.WriteLine ("Minimum iteration: {0}", result.) Lowestbreakiteration);

The output results are as follows:

It can also pass in the number of iterations and parallelloopstate as for the, by foreach<tsource> (ienumerable<tsource> source, action< TSource, ParallelLoopState, long> body), followed by a change in the example above

            string[] data = {"Str1", "str2", "Str3", "STR4", "STR5"};            Parallelloopresult result = parallel.foreach<string> (data, (STR, state, i) = =  {                  Console.WriteLine (" Iteration count: {0},{1} ", I, str);                  if (i > 3) state                      . Break ();              });            Console.WriteLine ("Whether complete: {0}", result.) iscompleted);            Console.WriteLine ("Minimum iteration: {0}", result.) Lowestbreakiteration);

The output results are as follows:

Iv. Parallel.Invoke ()

The Parallel.Invoke () method, which provides the task parallelism pattern. The Paraller.invoke () method allows you to pass an array of action delegates, where you can specify which methods should be run, as shown in the following example

            Parallel.Invoke (() =>{                thread.sleep (+);                Console.WriteLine ("Method1");            }, () =>{                Thread.Sleep (ten);                Console.WriteLine ("Method2");            });

The output results are as follows:

V. Conclusion

The Parallel.For () and Paraller.foreach () methods call the same code in each iteration, whereas the Parallel.Invoke () method allows different methods to be called simultaneously. Parallel.ForEach () is used for data parallelism, and Parallel.Invoke () is used for task parallelism;

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.