C # Advanced Programming reading Notes (15): task, thread, and synchronization one of the parallel classes

Source: Internet
Author: User

1,parallel class

The parallel class is a good abstraction for threads. This class is located in the System.Threading.Tasks namespace and provides parallelism for data and tasks.

The parallel class defines the parallel for and foreach static methods. For C # for and foreach statements, loops run from one thread. The parallel class uses multiple tasks, so multiple threads are used to complete the job.

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

2,parallel.invoke Method

The simplest way to try to run multiple methods in parallel is to use the parallel class's Invoke method to see the sample code:

Private Static void Main (string[] args)        {            Parallel.Invoke (()=>console.writeline (" eat "), () =>console.writeline (" sleeping "), () =>console.writeline ("  hit the peas ");            Console.readkey ();        }

Execution Result:

The Invoke method receives an array of action

 Public Static void Invoke (params action[] actions);

As you can see from the execution results, there is no specific order of execution.

The Parallel.Invoke method returns only after all the methods have been completed, does not guarantee that the method can start execution at the same time, and if one or more cores are busy, the underlying scheduling logic may delay execution of some methods.

3,parallel.for

The Parallel.For () method is similar to the FOR Loop statement for C #, and it is a task that executes multiple times. Using the Parallel.For () method, you can run iterations in parallel.

In the For () method, the first two parameters define the start and end of the loop. The third parameter is a action<int> delegate. An integer parameter is the number of iterations of a loop that is passed to the method that the delegate refers to. The return type of the Parallel.For () method is the Parallelloopresult structure, which provides information about whether the loop ends.

        Private Static voidMain (string[] args) {Parallelloopresult result= Parallel.For (0,Ten, i ={Console.WriteLine ($"{I},task:{task.currentid},thread:{thread.currentthread.managedthreadid}"); Thread.Sleep (Ten);            }); Console.WriteLine ($"Is completed: {result. IsCompleted}");        Console.readkey (); }

Execution Result:

4,parallel.foreach

The Parallel.ForEach () method traversal implements the collection of IEnumerable, which is similar to a ForEach statement but traverses asynchronously. There is also no definite traversal order here.

            string[] data = {"Zero"," One"," Both","three"," Four","Five","Six","Seven","Eight","Nine","Ten"}; Parallelloopresult result= parallel.foreach<string> (data, S ={Console.WriteLine (s); Thread.Sleep (Ten); });

Execution Result:

Zerofivetenonesixthreetwosevenfoureightnine

This article speaks very well: "Reading Notes". NET Parallel Programming Advanced Tutorial--parallel

C # Advanced Programming reading Notes (15): task, thread, and synchronization one of the parallel classes

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.