DEV Community

Ali Kolahdoozan
Ali Kolahdoozan

Posted on

Parallel Class in .NET ! – Part 1

Image description

CPU manufacturers are trying to add more cores to their processors to enable parallel computing. Parallel computing is a type of computation in which many calculations or processes are carried out simultaneously on different cores. Parallel computing can speed up a computational task by dividing it into smaller jobs that can be executed concurrently. Parallel computing has many applications in various fields, such as astrophysics, geoprocessing, risk management, video editing, and medical imaging. Therefore, we should know how to use parallelism features by coding so that we can take advantage of the power and performance of multicore processors and solve complex problems faster and more efficiently.

Parallelism in C# is the ability to run multiple tasks or operations concurrently on different processors or cores. Parallelism can improve the performance and responsiveness of applications that have computationally intensive or long-running workloads. C# provides various mechanisms and libraries to support parallel programming, such as tasks, threads, thread pools, parallel loops, parallel LINQ, and data structures for synchronization and lazy initialization.

Parallel class in C# is a static class that provides methods for parallel programming. Parallel programming is a way of executing multiple tasks or operations concurrently on different processors or cores. Parallel class can help you improve the performance and scalability of your applications by making use of all the available CPU resources. However, parallel programming also introduces some challenges and trade-offs, such as synchronization, load balancing, data partitioning, and exception handling. Therefore, you need to carefully design your parallel code and use appropriate options and techniques to optimize your CPU usage.

I am going to shed some light at the small portion of Parallelism in C# which is : Parallel Class in .NET !

Parallel class is defined in the System.Threading.Tasks namespace and has four main methods:

1- Parallel.For
2- Parallel.ForEach
3- Parallel.ForEachAsync
4- Parallel.Invoke

These methods allow you to create parallel loops and invoke multiple actions in parallel. Parallel class also supports cancellation, exception handling, loop state control, and custom partitioning.

Parallel.For
Parallel.For is a method in C# that allows you to create a parallel loop. A parallel loop is a loop that executes multiple iterations concurrently on different threads or cores. Parallel.For takes a collection or a range of values as input, and executes an action delegate for each element or value in parallel. Parallel.For can improve the performance and scalability of applications that have independent and CPU-bound workloads.

Parallel.ForEach
Parallel.ForEach is a method that executes a foreach loop in parallel, using multiple threads. Unlike a regular foreach loop that runs on a single thread and processes each item in the collection one by one, Parallel.ForEach runs on multiple threads and processes multiple items at the same time.

Parallel.ForEachAsync
Parallel.ForEachAsync is a new method in .NET 6 that allows you to execute an asynchronous action for each element of a source collection in parallel. It is similar to Parallel.ForEach but it supports async/await and cancellation tokens.

Some possible usage scenarios for Parallel.ForEachAsync are:
• Making multiple HTTP requests concurrently.
• Processing large files or streams asynchronously.
• Performing CPU-intensive calculations with async operations

Parallel.Invoke
Parallel.Invoke is a method in .NET that allows you to execute multiple actions in parallel. It takes an array of Action delegates as a parameter and runs them concurrently on different threads. It returns when all the actions are completed or an exception is thrown.

Parallel.Invoke can be useful when you want to parallelize operations that do not depend on each other or share data (learn.microsoft.com). For example, you can use Parallel.Invoke to perform some independent calculations or file operations.

Everything would be more understandable if we leave the theory aside and go for real examples. Follow below steps.

Create a New .NET 7 Console Application at first and name it : ParallelClassExercise

First step :

Image description

Second Step :

Image description

Last Step :

Image description

And then,

Image description

🥂 We have a Console Application now ! 🥂

Let’s start with a simple example :

As you can see, the Paralle.For has 12 overloads !

Image description
It starts with frominclusive that is an integer and toexclusive that is an Integer either. This means if I want to go from 0 to 100, the from should be 0 and to should be 100.

The Action can be a method so let’s create a simple Method to be able to use inside the For body.You can see my method and how to use it below.The parameter in the Action is an Index in the loop.

Image description
If I run, you will see something like the below screen shoot.

Image description

The result is not necessarily sequential, because everything gets done in parallel.

I can have the same result by following the Delegate way like below.

Image description
Another way is simply adding our action to the body of the loop like below.

Image description
If you need to have multi lines of code for any reason, follow the below way of implementation.

Image description

Let’s have a look at one of the useful Parallel.For overloads in detail. Imagine you want to manage the number concurrent scenarios in the loop, then you should add one parameter to be able to control the
MaxDegreeOfParallelism.If it sets to -1, then this means unlimited or if you set it to 1, then your loop would be run as a normal loop and totally sequential.

Image description

The last thing about Parallel.For is controlling the state of each iteration that might be so useful if you are working on a very CPU intensive scenario. Let’s have a look by an example.

Image description
I have added an state parameter and just printed it like above screen. You can check all the method and properties and of the state so easily by yourself. I just showed you how many are there below.

Image description

The rest of the overloads are the combination of what I have explained in this article so no need to mention and give you an example about each one by one here.

I will talk about Parallel.Foreach & Parallel.ForeachAsync in the Second Part soon.

Lazy to write 3-5 line of simple code ?. I have provided the Github link for you :

https://github.com/AliCharper/ParallelClassExercise

Wish you all the best...
We ❤️ .NET !
Ali

Top comments (0)