Multi-threaded Parallel class, multi-threaded parallel

Source: Internet
Author: User

Multi-threaded Parallel class, multi-threaded parallel

The Parallel class is an abstraction of threads. This class is located in the System. Threading. Tasks namespace and provides data and task concurrency.
The Paraller class defines the static methods For parallel data For and ForEach, and the static methods For concurrent task Invoke. The Parallel. For () and Parallel. ForEach () Methods call the same code in each iteration. Paraller. Invoke () allows different methods to be called.

1. Parallel.
The Parallel. For () method is similar to the for loop statement in the C # syntax and executes a task multiple times. However, this method runs iterations in parallel, and the iteration sequence is not defined.
In the Parallel. For () method, the first two parameters define the beginning and end of the loop, and the third parameter is an Action delegate. The Parallel. For method returns the ParallelLoopResult structure, which provides information about whether the loop ends.
Parallel. For has multiple overloaded versions and multiple generic overloaded versions.
Example:

     static void ForTest()        {            ParallelLoopResult plr =                Parallel.For(0,10,i => {                    Console.WriteLine("{0},task:{1},thread:{2}",i,Task.CurrentId,Thread.CurrentThread.ManagedThreadId);                    Thread.Sleep(5000);                });            if (plr.IsCompleted)                Console.WriteLine("completed!");        }

Output:
  

Tasks are not necessarily mapped to a thread. Threads can also be reused by different tasks.


The preceding example uses the Thread. Sleep method added in. NET 4.5, instead of the Task. Delay method. Task. Delay is an asynchronous (http://www.cnblogs.com/afei-24/p/6757361.html) method used to release threads for other tasks.
Example:

  static void ForTestDelay()        {            ParallelLoopResult plr =                Parallel.For(0, 10,async i => {                    Console.WriteLine("{0},task:{1},thread:{2}", i, Task.CurrentId, Thread.CurrentThread.ManagedThreadId);                    await Task.Delay(1000);                    Console.WriteLine("{0},task:{1},thread:{2}", i, Task.CurrentId, Thread.CurrentThread.ManagedThreadId);                });            if (plr.IsCompleted)                Console.WriteLine("completed!");            Console.ReadKey();        }

Output:
  
The above Code uses the await keyword for latency. The output result shows that the code before and after the latency runs in different threads. In addition, the delayed task no longer exists, leaving only the thread, and the previous thread is reused here. Another important aspect is that the For method of the Parallel class does not wait For a delay, but is completed directly. The parallel class only waits for the tasks it creates, rather than other background activities. Therefore, the above Code uses Console. ReadKey (); To keep the main thread running, otherwise the subsequent output may not be seen.

2. Stop Parallel. For in advance
An overloaded version of The For () method accepts parameters of the third Action <int, ParallelLoopState> delegate type. You can call the Break () or Stop () method of ParallelLoopState to Stop the loop.
Note: As mentioned above, the iteration sequence is not defined.
Example:

Static void ForStop () {ParallelLoopResult plr = Parallel. for (0, 10, (int I, ParallelLoopState pls) => {Console. writeLine ("{0}, task: {1}, thread: {2}", I, Task. currentId, Thread. currentThread. managedThreadId); if (I> 5) pls. break () ;}); Console. writeLine ("is completed: {0}", plr. isCompleted); Console. writeLine ("lowest stop index: {0}", plr. lowestBreakIteration );}

Output:
  
The iteration value is interrupted when it is greater than 5, but other started tasks are executed at the same time.


3. initialize each thread in Parallel.
The Parallel. For method uses multiple threads to execute a loop. If you need to initialize each thread, you can use the Parallel. For <TLocal> () method. In addition to the from and to values, the generic version of the Parallel. For method also accepts three delegate parameters:
The type of the first delegate parameter is Func <TLocal>. This method is only used to call every thread used for iteration.
The second delegate parameter defines the delegate for the loop body. The parameter type is Func <int, ParallelLoopState, TLocal, TLocal>. The first parameter is loop iteration. The second parameter ParallelLoopState allows loop stop. The third parameter accepts the value returned by the Func <TLocal> delegate from the preceding parameter, the delegate also needs to return a value of the TLocal type. This method is called for each iteration.
The third delegate parameter specifies a delegate Action <TLocal> and accepts the return value of the second delegate parameter. This method is used only for every thread that is used for iteration.

Example:

      static void ForInit()            {                ParallelLoopResult plr =                    Parallel.For(0,10,()=> {                        Console.WriteLine("init thread:{0},task:{1}",Thread.CurrentThread.ManagedThreadId,Task.CurrentId);                        return Thread.CurrentThread.ManagedThreadId.ToString();                    },                    (i, pls,strInit)=> {                        Console.WriteLine("body:{0},strInit:{1},thraed:{2},task:{3}",i,strInit,Thread.CurrentThread.ManagedThreadId,Task.CurrentId);                        return i.ToString();                    },                    (strI)=> {                        Console.WriteLine("finally {0}",strI);                    });            }

Output:
  


4. Parallel. ForEach
The Parallel. ForEach method traverses the set of IEnumerable, similar to foreach, but asynchronously traverses the set. The traversal order is not determined.

Example:

    static void ForeachTest()        {            string[] data = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve" };            ParallelLoopResult plr =  Parallel.ForEach<string>(data, s =>            {                Console.WriteLine(s);            });            if (plr.IsCompleted)                Console.WriteLine("completed!");        }

 

 

If you need to interrupt, you can use the ForEach overload version and the ParallelLoopState parameter.
Access indexer:

    ParallelLoopResult plr1 = Parallel.ForEach<string>(data, (s,pls,l) =>            {                Console.WriteLine("data:{0},index:{1}",s,l);            });

 

5. Parallel. Invoke
If multiple tasks run in Parallel, you can use the Parallel. Invoke method. This method allows passing an Action delegate array.

    static void ParallerInvoke()        {            Action[] funs = { Fun1,Fun2};            Parallel.Invoke(funs);        }        static void Fun1()        {            Console.WriteLine("f1");            Console.WriteLine("task:{0},thread:{1}", Task.CurrentId, Thread.CurrentThread.ManagedThreadId);        }        static void Fun2()        {            Console.WriteLine("f2");            Console.WriteLine("task:{0},thread:{1}", Task.CurrentId, Thread.CurrentThread.ManagedThreadId);        }

 

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.