Home Backend Development C#.Net Tutorial An example introduction to the Parallel class of C# parallel tasks

An example introduction to the Parallel class of C# parallel tasks

Jun 23, 2017 pm 03:13 PM
.net Task parallel

1. Parallel class

The Parallel class provides data and task parallelism;

2. Paraller.For()

The Paraller.For() method is similar The for loop statement in C# also executes a task multiple times. Iterations can be run in parallel using the Paraller.For() method. The order of the iterations is not defined.

In the For() method, the first two parameters are fixed. These two parameters define the beginning and end of the loop. First describe its first method For(int,int,Action). The first two parameters represent the beginning and introduction of the loop. The third parameter is a delegate. The integer parameter is the number of iterations of the loop. This parameter is passed The method given to the delegate. The return type of the Paraller.For() method is a ParallelLoopResult structure, which provides information about whether the loop has ended and the index of the lowest iteration (returns an integer representing the lowest iteration from which the Break statement was called). First write an example:

            ParallelLoopResult result = Parallel.For(0, 10, i =>{
                Console.WriteLine("迭代次数:{0},任务ID:{1},线程ID:{2}", i, Task.CurrentId, Thread.CurrentThread.ManagedThreadId);
                Thread.Sleep(10);
            });

            Console.WriteLine("是否完成:{0}", result.IsCompleted);
            Console.WriteLine("最低迭代:{0}", result.LowestBreakIteration);
Copy after login

The output result is as follows:

You can see that the delegate method has been run 10 times, in order It is also not guaranteed. But no data comes out for the lowest iteration. This is because it returns the integer of the lowest iteration that calls the Break statement. We do not have a break here. If you need to interrupt the For() method early during execution, you can use ParallelLoopState to implement it, For(int,int,Action). Change the above example:

            ParallelLoopResult result = Parallel.For(0, 10, (i, state) =>{
                Console.WriteLine("迭代次数:{0},任务ID:{1},线程ID:{2}", i, Task.CurrentId, Thread.CurrentThread.ManagedThreadId);
                Thread.Sleep(10);if (i > 5)
                    state.Break();
            });

            Console.WriteLine("是否完成:{0}", result.IsCompleted);
            Console.WriteLine("最低迭代:{0}", result.LowestBreakIteration);
Copy after login

The output result is as follows:

3. Parallel.ForEach()

The Paraller.ForEach() method traverses the collection that implements IEnumerable. Its method is similar to the foreach statement, but it traverses in an asynchronous manner, and the traversal order is not determined here. First describe its first method, Paraller.ForEach(IEnumerable,Action), first look at the following example;

            string[] data = { "str1", "str2", "str3" };
            ParallelLoopResult result = Parallel.ForEach<string>(data, str =>  {
                  Console.WriteLine(str);
              });
            Console.WriteLine("是否完成:{0}", result.IsCompleted);
            Console.WriteLine("最低迭代:{0}", result.LowestBreakIteration);
Copy after login

The output results are as follows:

##It can also pass in the iteration number and ParallelLoopState like For, the method is ForEach(IEnumerable source, Action body), then change

            string[] data = { "str1", "str2", "str3", "str4", "str5" };
            ParallelLoopResult result = Parallel.ForEach<string>(data, (str, state, i) =>  {
                  Console.WriteLine("迭代次数:{0},{1}", i, str);                  if (i > 3)
                      state.Break();
              });
            Console.WriteLine("是否完成:{0}", result.IsCompleted);
            Console.WriteLine("最低迭代:{0}", result.LowestBreakIteration);
Copy after login
in the above example and the output result is as follows:

4. Parallel.Invoke()

Parallel.Invoke() method, which provides task parallelism mode. The Paraller.Invoke() method allows passing an Action delegate array, in which you can specify the method that should be run. See the following example

            Parallel.Invoke(() =>{
                Thread.Sleep(100);
                Console.WriteLine("method1");
            }, () =>{
                Thread.Sleep(10);
                Console.WriteLine("method2");
            });
Copy after login
The output result is as follows:

5. Conclusion

The Parallel.For() and Paraller.ForEach() methods call the same code in each iteration, while the Parallel.Invoke() method allows different calls to be made at the same time. Methods. Parallel.ForEach() is used for data parallelism, and Parallel.Invoke() is used for task parallelism;

The above is the detailed content of An example introduction to the Parallel class of C# parallel tasks. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1252
24
How to complete the horror corridor mission in Goat Simulator 3 How to complete the horror corridor mission in Goat Simulator 3 Feb 25, 2024 pm 03:40 PM

The Terror Corridor is a mission in Goat Simulator 3. How can you complete this mission? Master the detailed clearance methods and corresponding processes, and be able to complete the corresponding challenges of this mission. The following will bring you Goat Simulator. 3 Horror Corridor Guide to learn related information. Goat Simulator 3 Terror Corridor Guide 1. First, players need to go to Silent Hill in the upper left corner of the map. 2. Here you can see a house with RESTSTOP written on the roof. Players need to operate the goat to enter this house. 3. After entering the room, we first go straight forward, and then turn right. There is a door at the end here, and we go in directly from here. 4. After entering, we also need to walk forward first and then turn right. When we reach the door here, the door will be closed. We need to turn back and find it.

Fix: Operator denied request error in Windows Task Scheduler Fix: Operator denied request error in Windows Task Scheduler Aug 01, 2023 pm 08:43 PM

To automate tasks and manage multiple systems, mission planning software is a valuable tool in your arsenal, especially as a system administrator. Windows Task Scheduler does the job perfectly, but lately many people have reported operator rejected request errors. This problem exists in all iterations of the operating system, and even though it has been widely reported and covered, there is no effective solution. Keep reading to find out what might actually work for other people! What is the request in Task Scheduler 0x800710e0 that was denied by the operator or administrator? Task Scheduler allows automating various tasks and applications without user input. You can use it to schedule and organize specific applications, configure automatic notifications, help deliver messages, and more. it

How to pass the Imperial Tomb mission in Goat Simulator 3 How to pass the Imperial Tomb mission in Goat Simulator 3 Mar 11, 2024 pm 01:10 PM

Goat Simulator 3 is a game with classic simulation gameplay, allowing players to fully experience the fun of casual action simulation. The game also has many exciting special tasks. Among them, the Goat Simulator 3 Imperial Tomb task requires players to find the bell tower. Some players are not sure how to operate the three clocks at the same time. Here is the guide to the Tomb of the Tomb mission in Goat Simulator 3! The guide to the Tomb of the Tomb mission in Goat Simulator 3 is to ring the bells in order. Detailed step expansion 1. First, players need to open the map and go to Wuqiu Cemetery. 2. Then go up to the bell tower. There will be three bells inside. 3. Then, in order from largest to smallest, follow the familiarity of 222312312. 4. After completing the knocking, you can complete the mission and open the door to get the lightsaber.

How to do the rescue Steve mission in Goat Simulator 3 How to do the rescue Steve mission in Goat Simulator 3 Feb 25, 2024 pm 03:34 PM

Rescue Steve is a unique task in Goat Simulator 3. What exactly needs to be done to complete it? This task is relatively simple, but we need to be careful not to misunderstand the meaning. Here we will bring you the rescue of Steve in Goat Simulator 3 Task strategies can help you better complete related tasks. Goat Simulator 3 Rescue Steve Mission Strategy 1. First come to the hot spring in the lower right corner of the map. 2. After arriving at the hot spring, you can trigger the task of rescuing Steve. 3. Note that there is a man in the hot spring. Although his name is Steve, he is not the target of this mission. 4. Find a fish named Steve in this hot spring and bring it ashore to complete this task.

Where can I find Douyin fan group tasks? Will the Douyin fan club lose level? Where can I find Douyin fan group tasks? Will the Douyin fan club lose level? Mar 07, 2024 pm 05:25 PM

TikTok, as one of the most popular social media platforms at the moment, has attracted a large number of users to participate. On Douyin, there are many fan group tasks that users can complete to obtain certain rewards and benefits. So where can I find Douyin fan club tasks? 1. Where can I view Douyin fan club tasks? In order to find Douyin fan group tasks, you need to visit Douyin's personal homepage. On the homepage, you will see an option called "Fan Club." Click this option and you can browse the fan groups you have joined and related tasks. In the fan club task column, you will see various types of tasks, such as likes, comments, sharing, forwarding, etc. Each task has corresponding rewards and requirements. Generally speaking, after completing the task, you will receive a certain amount of gold coins or experience points.

Timing Analysis Pentagon Warrior! Tsinghua University proposes TimesNet: leading in prediction, filling, classification, and detection Timing Analysis Pentagon Warrior! Tsinghua University proposes TimesNet: leading in prediction, filling, classification, and detection Apr 11, 2023 pm 07:34 PM

Achieving task universality is a core issue in the research of basic deep learning models, and is also one of the main focuses in the recent direction of large models. However, in the field of time series, various types of analysis tasks vary greatly. There are prediction tasks that require fine-grained modeling and classification tasks that require extracting high-level semantic information. How to build a unified deep basic model to efficiently complete various timing analysis tasks has not yet been established. To this end, a team from the School of Software of Tsinghua University conducted research on the basic issue of timing change modeling and proposed TimesNet, a task-universal timing basic model. The paper was accepted by ICLR 2023. Author list: Wu Haixu*, Hu Tengge*, Liu Yong*, Zhou Hang, Wang Jianmin, Long Mingsheng Link: https://ope

How to stop Task Manager process updates and kill tasks more easily in Windows 11 How to stop Task Manager process updates and kill tasks more easily in Windows 11 Aug 20, 2023 am 11:05 AM

How to Pause Task Manager Process Updates in Windows 11 and Windows 10 Press CTRL+Window Key+Delete to open Task Manager. By default, Task Manager will open the Processes window. As you can see here, all the apps are endlessly moving around and it can be hard to point them down when you want to select them. So, press CTRL and hold it, this will pause the task manager. You can still select apps and even scroll down, but you must hold down the CTRL button at all times.

Everything you need to know about the End Task option in the Windows 11 taskbar Everything you need to know about the End Task option in the Windows 11 taskbar Aug 25, 2023 pm 12:29 PM

Frozen or unresponsive programs are easy to kill from Task Manager. But Microsoft has recently provided users with the facility to terminate these tasks directly from the taskbar. While the option isn't rolled out to everyone, it's easily available if you have the Windows Insider build. Here's everything you need to enable the End Task button and close tasks from the taskbar. How to Get the End Task Button from the Taskbar to Kill Apps Currently, the option to enable the End Task button for taskbar apps is only available as a developer option for users with Windows Insider builds. However, this may change in an upcoming feature update as it will be rolled out to users globally on the stable version. If you still

See all articles