Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use the Parallel class of C # multithreading

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article editor for you a detailed introduction of "C# multithreading Parallel class how to use", the content is detailed, the steps are clear, the details are handled properly, I hope this "C# multithreading Parallel class how to use" article can help you solve doubts, the following follow the editor's ideas slowly in-depth, together to learn new knowledge.

The Parallel class is an abstraction of threads. This class is located in the System.Threading.Tasks namespace and provides data and task parallelism.

The Paraller class defines static methods for data parallel For and ForEach, and static methods for task parallel Invoke. The Parallel.For () and Parallel.ForEach () methods call the same code in each iteration, and Paraller.Invoke () allows different methods to be called.

1.Parallel.For

The Parallel.For () method is similar to the for loop statement of the C # syntax, performing a task multiple times. However, this method runs iterations in parallel, and the order of iterations 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 return type of the Parallel.For method is 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 (0Power10) I = > {Console.WriteLine ("{0}, task: {1}, thread: {2}", iMagnum Task.CurrentIdRead. CurrentThread.ManagedThreadId); Thread.Sleep (5000);}) If (plr.IsCompleted) Console.WriteLine ("completed!");

Output:

The task does not necessarily map to a thread. Threads can also be reused by different tasks.

The above example uses the new Thread.Sleep method in .NET 4.5 instead of the Task.Delay method. Task.Delay is an http://www.cnblogs.com/afei-24/p/6757361.html) method that frees threads for use by other tasks.

Example:

Static void ForTestDelay () {ParallelLoopResult plr = Parallel.For (0,10 Task.CurrentId 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 to delay, and the output shows that the code before and after the delay is running in a different thread. And the delayed task no longer exists, leaving only threads, and the previous threads are reused here. Another important aspect is that the For method of the Parallel class does not wait for a delay, but completes directly. The parallel class waits only for the tasks it creates, not for other background activities. So the above code uses Console.ReadKey (); keep the main thread running, otherwise you probably won't see the rest of the output.

two。 Stop Parallel.For ahead of time

An overloaded version of the For () method accepts parameters of the third Action delegate type. Using this method, you can call the Break () or Stop () methods of ParallelLoopState to stop the loop.

Note that as mentioned earlier, the order of iterations is not defined.

Example:

Static void ForStop () {ParallelLoopResult plr = Parallel.For (int iParallelLoopState 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 ("minimum 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.For

The Parallel.For method uses multiple threads to execute the loop, and if you need to initialize each thread, you can use the Parallel.For () method. In addition to the values corresponding to from and to, the generic version of the Parallel.For method accepts three delegate parameters:

The first delegate parameter is of type Func, and this method is called only once for each thread used to perform the iteration.

The second delegate parameter defines the delegate for the loop body. The parameter type is Func. The first parameter is a loop iteration, the second parameter ParallelLoopState allows the loop to be stopped, and the third parameter accepts the value returned from the above parameter delegate Func, which also returns a value of type TLocal. This method is called for each iteration.

The third delegate parameter specifies a delegate Action that accepts the return value of the second delegate parameter. This method is called only once for each thread used to perform the iteration.

Example:

Static void ForInit () {ParallelLoopResult plr = Parallel.For (0Power10, () = > {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}"); return i.ToString () }, (strI) = > {Console.WriteLine ("finally {0}" strI);});}

Output:

4.Parallel.ForEach

The Parallel.ForEach method traverses the collection that implements IEnumerable, similar to foreach, but traverses asynchronously. 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 (data, s = > {Console.WriteLine (s);}) If (plr.IsCompleted) Console.WriteLine ("completed!");

If you need an interrupt, you can use the overloaded version of ForEach and the parameter ParallelLoopState.

Access indexer:

ParallelLoopResult plr1 = Parallel.ForEach (data, (SCHEROPERING 1) = > {Console.WriteLine ("data: {0}, index: {1}", SJONL);}); 5.Parallel.Invoke

If multiple tasks are running in parallel, you can use the Parallel.Invoke method. This method allows you to pass an array of Action delegates.

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) } read here, this article "how to use the Parallel class of C# multithreading" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself. If you want to know more about related articles, welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report