Brief introduction
Another way to implement multithreading in C # is to use the parallel class.
In. NET4, another new abstraction thread is the parallel class. This class defines the parallel for and foreach static methods. In the language defined for for and foreach, the loop runs from one thread. The parallel class uses multiple tasks, so multiple threads are used to complete the job.
In the previous article, we have made a certain interpretation of the task, interested friends can go to see.
The Parallel.For () and Parallel.ForEach () methods call the same method multiple times, whereas the Parallel.Invoke () method allows different methods to be called simultaneously.
Use the Parallel.For () method to use the basic method
The Parallel.For () method is similar to the For Loop for C #, and also performs a task multiple times. Using the Parallel.For () method, you can run iterations in parallel. The order of the iterations is undefined.
In the For () method, the first two parameters define the start and end of the loop. Examples are from 0 iterations to 9. The 3rd parameter is an action < int > delegate. An integer parameter is the number of iterations of a loop that is passed to the < method that the action int > delegates reference. The return type of the Parallel.For () method is the Paralleloopresult structure, which provides information about whether the loop ends.
parallelloopresult result = Parallel (0 , 10 , i + = {Co Nsole ( "{0}, Task: {1}, Thread: {2}" , I, Task, Thread ) ; }) Console (Result) ; Console () ;
In the method body of Parallel.For (), write the index, task identifier, and thread identifier to the console. As you can see from the output below, the order of execution for each thread is not guaranteed because the new tasks and threads are opened for Each loop.
Interrupt loop
Similar to the for () loop, the Parallel.For () method can also interrupt the execution of a loop.
An overloaded version of the Parallel.For () method accepts the 3rd action < int, the > parameter of the ParallelLoopState type. Using these parameters to define a method, you can call the break () or stop () method of paralleloopstate to affect the result of the loop.
Note that the order of the iterations is undefined.
Parallelloopresult result = Parallel.For(0, ten, (int i, parallelloopstate pls) = {Console.WriteLine ("I: { 0}, Task: {1} ", I, Task.currentid); Thread.Sleep (ten); if (i > ) {pls. Break (); } });Console.WriteLine(result.) iscompleted);Console.WriteLine("Lowest break iteration: {0}", result.) Lowestbreakiteration);Console.ReadKey();
Here's the result:
The application runs this time and the iteration is interrupted at a value greater than 15 o'clock, but other tasks can run at the same time, and tasks with other values can be run. With the Lowestbreakiteration property, you can ignore the results of other tasks.
Parallel.For
<Tlocal
>Method
The Parallel.For () method may use several threads to perform loops. If you need to initialize each thread, you can use the Parallel.For < tlocal > method. The generic version of the for () method accepts 3 delegate parameters in addition to the From and to values.
The type of the first parameter is func < tlocal > , because the example here uses a string for tlocal, so the method needs to be defined as a func < string > , that is, a method that returns a string. This method is called only once for each thread that is used to perform the iteration.
The second delegate parameter defines the delegate for the loop body. In the example, the type of the parameter is func < int, ParallelLoopState, String, string > . Where the first parameter is a loop iteration, the second parameter, ParallelLoopState, allows the loop to stop, as described earlier. The loop body method receives the value returned from the Init method through the 3rd parameter, and the loop body method also needs to return a value whose type is defined with the generic for parameter.
The last parameter of the for () method specifies a delegate action < tlocal > ; In this example, a string is received. This method is called only once for each thread, which is a thread exit method.
Parallel. for<string> (0, -, () = {Console. WriteLine("Init thread {0},\t task {1}", Thread. CurrentThread. Managedthreadid, Task. CurrentID);return string. Format("T{0}", Thread. CurrentThread. Managedthreadid);}, (i, pls, str) = = {Console. WriteLine("Body I {0} \ t str {1} \ t thread {2} \ t task {3}", I, str, Thread. CurrentThread. Managedthreadid, Task. CurrentID);Thread. Sleep(Ten);return string. Format("I \t{0}"I;}, (str) + = {Console. WriteLine("finally\t {0}", str);});Console. ReadKey();
Program Run Result:
Note:
Parallel.For < tlocal > method (Int32, Int32, func < tlocal > , func < Int32, ParallelLoopState, Tlocal, Tlocal > , Action < tlocal > )
Type parameter
Tloca
The type of thread-local data.
Parameters
Frominclusive
Type: System.Int32
Start index (inclusive).
Toexclusive
Type: System.Int32
End index (not included).
LocalInit
Type: System.Func < tlocal >
A function delegate that returns the initial state of the local data for each task.
Body
Type: System.Func < Int32, ParallelLoopState, tlocal, tlocal >
The delegate that will be called once for each iteration.
Localfinally
Type: system.action < tlocal >
A delegate that performs a final action on the local state of each task.
return value
Type: System.Threading.Tasks.ParallelLoopResult
In the iteration range (frominclusive,toexclusive), the body delegate is called once for each value. It is provided with the following parameters: Number of iterations (Int32), parallelloopstate instances that can be used to exit the loop prematurely, and some local states that can be shared between iterations that are executed on the same thread.
Invokes the LocalInit delegate once for each task that participates in the loop execution and returns the initial local state of each task. These initial states are passed to the first body that is called on the task. Then, each subsequent body call returns a potentially modified state value that is passed to the next body call. Finally, the last body call on each task returns the status value passed to the Localfinally delegate. Each task invokes the Localfinally delegate once to perform a final operation on the local state of each task. This delegate can be called synchronously by multiple tasks, so you must synchronize access to any shared variables.
The Parallel.For method may use more tasks than the thread in which it is executing, and is completed as an existing task and replaced by a new task. This gives the underlying TaskScheduler object the opportunity to add, change, or remove threads from the service loop.
If frominclusive is greater than or equal to Toexclusive, the method returns immediately without having to perform any iterations.
Use the Parallel.ForEach () method to use the basic method
The Parallel.ForEach () method traversal implements the collection of IEnumerable, in a manner similar to a ForEach statement but traversed asynchronously. There is also no definite traversal order here.
string[] data = { "zero" , , , "three" , "four" , , " six ", " seven ", " eight ", " Nine ", " ten ", Span class= "hljs-string" > "eleven" , "twelve" }; Parallelloopresult result = Parallel.foreach<string> ( Data, (s) = {Console.WriteLine (s); }); console . readkey () ;
Results:
Interrupt loop
If you need to break the loop, you can use the overloaded version of the foreach () method and the ParallelLoopState parameter. The same way as the previous for () method. An overloaded version of the ForEach () method can also be used to access the indexer to get the number of iterations, as follows:
string[] data = {"Zero","One","both","three","Four","Five","Six","Seven","Eight","Nine","Ten","Eleven","Twelve"}; Parallelloopresult result = parallel.foreach<string> (data, (s, pls, l) = = {Console.WriteLine ("{0}\t{1}", S, l); if (L > ten) {pls. Break (); } }); Console. WriteLine ("Lowest break iteration: {0}", result.) lowestbreakiteration); Console. ReadKey ();
Results:
Using the Parallel.Invoke () method
If multiple tasks should run in parallel, you can use the Parallel.Invoke () method. The Parallel.Invoke () method allows you to pass an array of action delegates, where you can specify which methods should be run.
The sample code passes the Foo () and Bar () methods to be called in parallel:
staticvoid Main(string[] args) { Parallel.Invoke(Foo, Bar); Console.ReadKey(); } staticvoid Foo() { Console.WriteLine("Foo"); } staticvoid Bar() { Console.WriteLine("Bar"); }
Results:
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
[Deep learning C #] C # How to implement Multithreading: using the Parallel class