Create Parallel Loop in C#

Visual Studio

In C#, you can use the Parallel.For loop to execute a loop in parallel. This can be useful for performing tasks that can be done concurrently, such as processing elements in an array or performing independent calculations. Here's an example of how to create a parallel loop in C#:

using System;
using System.Threading.Tasks;

class Program
{
    static void Main()
    {
        int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

        Parallel.For(0, numbers.Length, i =>
        {
            Console.WriteLine($"Task {i} is processing element {numbers[i]}");
        });

        Console.WriteLine("Parallel loop complete.");
    }
}

The Parallel.For method takes three arguments: the start index, the end index (exclusive), and an action to perform on each index.

In this example, we have an array of numbers from 1 to 10. We use Parallel.For to iterate over the array indices (from 0 to numbers.Length - 1).

The lambda expression i => { ... } represents the action to be performed on each index i. In this case, it prints a message indicating which task is processing which element.

The output may not be in sequential order since tasks are executed concurrently.

Make sure to add a reference to the System.Threading.Tasks assembly in your project.

Keep in mind that parallel processing is not always suitable for all types of tasks, and it's important to consider the nature of the task and potential thread safety issues. Always test and profile your code to ensure it provides the desired performance improvements.

Comments
Loading...
Sorry! No comment found:(

There is no comment to show for this.

Leave your comment
Tested Versions
  • .NET 4.6
  • Visual Studio 2022