search
HomeBackend DevelopmentC#.Net TutorialAn example introduction to the Parallel class of C# parallel tasks

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);

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);

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);</string>

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);</string>
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");
            });
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
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
Developing with C# .NET: A Practical Guide and ExamplesDeveloping with C# .NET: A Practical Guide and ExamplesMay 12, 2025 am 12:16 AM

C# and .NET provide powerful features and an efficient development environment. 1) C# is a modern, object-oriented programming language that combines the power of C and the simplicity of Java. 2) The .NET framework is a platform for building and running applications, supporting multiple programming languages. 3) Classes and objects in C# are the core of object-oriented programming. Classes define data and behaviors, and objects are instances of classes. 4) The garbage collection mechanism of .NET automatically manages memory to simplify the work of developers. 5) C# and .NET provide powerful file operation functions, supporting synchronous and asynchronous programming. 6) Common errors can be solved through debugger, logging and exception handling. 7) Performance optimization and best practices include using StringBuild

C# .NET: Understanding the Microsoft .NET FrameworkC# .NET: Understanding the Microsoft .NET FrameworkMay 11, 2025 am 12:17 AM

.NETFramework is a cross-language, cross-platform development platform that provides a consistent programming model and a powerful runtime environment. 1) It consists of CLR and FCL, which manages memory and threads, and FCL provides pre-built functions. 2) Examples of usage include reading files and LINQ queries. 3) Common errors involve unhandled exceptions and memory leaks, and need to be resolved using debugging tools. 4) Performance optimization can be achieved through asynchronous programming and caching, and maintaining code readability and maintainability is the key.

The Longevity of C# .NET: Reasons for its Enduring PopularityThe Longevity of C# .NET: Reasons for its Enduring PopularityMay 10, 2025 am 12:12 AM

Reasons for C#.NET to remain lasting attractive include its excellent performance, rich ecosystem, strong community support and cross-platform development capabilities. 1) Excellent performance and is suitable for enterprise-level application and game development; 2) The .NET framework provides a wide range of class libraries and tools to support a variety of development fields; 3) It has an active developer community and rich learning resources; 4) .NETCore realizes cross-platform development and expands application scenarios.

Mastering C# .NET Design Patterns: From Singleton to Dependency InjectionMastering C# .NET Design Patterns: From Singleton to Dependency InjectionMay 09, 2025 am 12:15 AM

Design patterns in C#.NET include Singleton patterns and dependency injection. 1.Singleton mode ensures that there is only one instance of the class, which is suitable for scenarios where global access points are required, but attention should be paid to thread safety and abuse issues. 2. Dependency injection improves code flexibility and testability by injecting dependencies. It is often used for constructor injection, but it is necessary to avoid excessive use to increase complexity.

C# .NET in the Modern World: Applications and IndustriesC# .NET in the Modern World: Applications and IndustriesMay 08, 2025 am 12:08 AM

C#.NET is widely used in the modern world in the fields of game development, financial services, the Internet of Things and cloud computing. 1) In game development, use C# to program through the Unity engine. 2) In the field of financial services, C#.NET is used to develop high-performance trading systems and data analysis tools. 3) In terms of IoT and cloud computing, C#.NET provides support through Azure services to develop device control logic and data processing.

C# .NET Framework vs. .NET Core/5/6: What's the Difference?C# .NET Framework vs. .NET Core/5/6: What's the Difference?May 07, 2025 am 12:06 AM

.NETFrameworkisWindows-centric,while.NETCore/5/6supportscross-platformdevelopment.1).NETFramework,since2002,isidealforWindowsapplicationsbutlimitedincross-platformcapabilities.2).NETCore,from2016,anditsevolutions(.NET5/6)offerbetterperformance,cross-

The Community of C# .NET Developers: Resources and SupportThe Community of C# .NET Developers: Resources and SupportMay 06, 2025 am 12:11 AM

The C#.NET developer community provides rich resources and support, including: 1. Microsoft's official documents, 2. Community forums such as StackOverflow and Reddit, and 3. Open source projects on GitHub. These resources help developers improve their programming skills from basic learning to advanced applications.

The C# .NET Advantage: Features, Benefits, and Use CasesThe C# .NET Advantage: Features, Benefits, and Use CasesMay 05, 2025 am 12:01 AM

The advantages of C#.NET include: 1) Language features, such as asynchronous programming simplifies development; 2) Performance and reliability, improving efficiency through JIT compilation and garbage collection mechanisms; 3) Cross-platform support, .NETCore expands application scenarios; 4) A wide range of practical applications, with outstanding performance from the Web to desktop and game development.

See all articles

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

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)