c sharp

C# Parallel Foreach

In this article, we will be focusing on the parallel Foreach loop in the C# programming language. The word parallel in C# programming comes from the concept of threading tasks, which means that when we are performing more than one task simultaneously, we can use the threading task library to call for the Task parallel library to get parallel for, Foreach loops to work over these tasks as they are more efficient and less time consuming as compared to normal sequential for and Foreach loops. The Parallel Foreach loop divides the tasks and runs the iterations in more than one stream to get to the end goal. The Parallel Foreach is only used when a process is iteratively called for input and is co-dependent on other operations as it increases the pace of processes.

Now we will perform several examples to clarify and increase comprehension of the Parallel Foreach loop in the C# programming language.

Example 01: Adding Numbers to a List Using the Parallel Foreach Loop in Ubuntu 20.04

In this example, we will write a C# program to add numbers to a list using the parallel Foreach loop and mark the number of threads simultaneously assigned to each step. We will have to use different libraries like the threading task and Link to access the monitoring and efficiency of the parallel for each loop. We will be performing this example in the Ubuntu 20.04 environment.g

In the above code, we have generated a list using the parallel for each loop in which the numbers were assigned to the list with the help of the Range function. Then we also printed the thread ids at every step to monitor the number of threads used while assigning values to the list. After running this program file in our command line terminal, we will get the following output:

The output suggests that the list was assigned 5 values, and during this process, two threads were used, which created a time difference in executing this task. If we can use a simple sequential Foreach loop, the task would have been done in a single thread, and the execution would be greater than the execution time of the parallel Foreach loop. Although this would vary as it depends on the size of the task at hand as the parallel foreach loop is more convenient for the larger size of the task and processing because it divides the task into multiple threads and works on the “divide and conquer” approach.

Example 02: Controlling Number of Threads Using Parallel Foreach Loop in Ubuntu 20.04

In this example, we will be controlling the creation of the number of threads when a parallel Foreach loop is executed. The task threading library gives us access to a property labeled “Max Degree Of Parallelism” that controls the parallel operations of the Parallel Options class and assigning a value to this property defines the number of parallel operations to be executed during the program. This property is sent to the parallel Foreach loop through an argument. We will create a C# program to assign numbers to a list and define the number of threads for executing this task.

As we can see that the total number of threads used in executing this task was only 2, as we fixed this number by assigning value to the “Max Degree of Parallelism.” In case of a huge amount of data processing, we can vary the value assigned to the Max Degree of Parallelism; this will help us divide the processing power equally and efficiently among the sub-tasks or parallel operations.

Example 03: Printing List with String Variables Using the Parallel Foreach Loop in a C# Program in Ubuntu 20.04

In this example, we will be printing items of a list with string variables by using the parallel Foreach loop in a C# program in the Ubuntu 20.04 environment. We will first initialize a list and assign values to it manually and then print all its elements as the output using the parallel foreach loop.

In the above code, we made a list named continents and added names of the continents to the list before using the parallel for each loop. We added the threading task library in order to use the parallel Foreach loop for our code. The parallel foreach method takes in the list and a new object as a parameter to store the values temporarily for each iteration. After executing this code file on our command line terminal, we will get the list of the names of the continents that we saved earlier in our list.

Example 04: Comparing Traditional Foreach Loop with Sequential Using Parallel Foreach Loop in C# in Ubuntu 20.04

In this example, we will be comparing the traditional Foreach loop with its sequential property with the parallel Foreach loop by doing a similar task with both the loops. The execution time of both the loops will be different because of their different approach to the task. We will print the contents of the list, which will be initialized before the operation, using the traditional Foreach loop with its sequential property and the parallel for each loop.

In the above C# program, we are using a normal Foreach loop and a parallel Foreach loop and calculating the time taken to execute the task by both the loops; we will use the stopwatch class from the C# programming language’s “Diagnostics” library. The stopwatch class has a “StartNew()” method, which starts the stopwatch, and the elapsed() function is used to stop the stopwatch. Both these functions were made accessible by making an object of the StopWatch class.

The output shows that the traditional Foreach loop took less time in executing the task than the Parallel Foreach loop. The reason is that the execution of the task is best suited for a single thread operation, and creating multiple threads for this task would be time-consuming, but if the list would have comprised thousands of data, then the execution time would be vice versa because in that scenario threading the task would be efficient and time-saving. So, when using the Parallel Foreach loop, we have to observe the size of the processing power required for that operation and consider which will be the suitable loop for that operation.

Conclusion:

We discussed the parallel Foreach loop in the C# programming language. In this article, the meaning of the name “Parallel” was discussed, as well as the practical differences between a parallel Foreach loop and a standard Foreach loop. Then we implemented several examples of the Parallel Foreach loop in the Ubuntu 20.04 environment to grasp more clarity on the topic. We concluded that using a parallel foreach loop has to be monitored while programming as it can go either way due to its threading mechanism; the task is divided, which would be time-consuming in the case of a smaller task.

About the author

Aqsa Yasin

I am a self-motivated information technology professional with a passion for writing. I am a technical writer and love to write for all Linux flavors and Windows.