Parallel Execution - Loops

 

Foreach

Foreach is used to iterate over a collection or an array of objects or values; it can be anything from a simple list of values to a rows in a dataset table.

When using a foreach loop, you don’t have to know the number of elements that the loop will iterate over because it will iterate over all elements in an array or a collection, unless you explicitly end the loop prematurely.

The following code will loop over the animals in the array.

string[] animals = { "cat", "dog", "bird" };

foreach (string animal in animals)

{

    // Code to execute

}

For

A for loop is a way to iterate over a set of values until the given expression evaluates to false. A for loop has three parts: a start value for the loop, an expression telling the loop when to stop, and a counter.

[int i = 0] is the start value, [i < 100] is the condition that makes the loop iterate 100 times, [i++] is the iterator.

for (int i = 0; i < 100; i++)

{

    // Code to execute a hundred times

}

Parallel Execution

In some cases you might find that the application is executing poorly because it has to execute several loops one after the other. This can significantly impact the user experience when the user has to wait for these loops to finish.

Wouldn’t it be great if there was a way to execute all these loops in parallel on separate threads? Well, in Visual Studio 2012 you can. By calling the ForEach method on the static Parallel class and pass it an Action of TSource.

Parallel Foreach

The Parallel class in the Task Parallel Library contains a number of methods that can be used if you want to execute several tasks simultaneously, such as executing loops in parallel.

If you have a need to run loops in parallel, you can do so using the Parallel.For or Parallel.Foreach methods; both have many overloads for different scenarios.

The simplest version of the overloaded ForEach method takes two parameters one collection of type IEnumerable<TSource> that you want to iterate over and one Action<TSource> that is the delegate function that will be executed once per iteration.

private void ParallelLoops_Click(object sender, RoutedEventArgs e)

{

    var students = new List<StaticStudent>();

    students.Add(new StaticStudent());

    Parallel.ForEach(students, student => ParallelForeach(student));

}

 

private void ParallelForeach(StaticStudent student)

{

    Console.WriteLine(student.FirstName);    

}

Parallel For

The from and to parameters of the loop are of the type Int32 and the index parameter is executed as an Action<Int32> once per iteration.

When the call to the ParallelFor method has finished the array storing the result will hold the square root of all the indices.

private void ParallelLoops_Click(object sender, RoutedEventArgs e)

{

    double[] array = ParallelFor();

}

 

private double[] ParallelFor()

{

    int from = 0;

    int to = 500000;

    double[] array = new double[to];

    Parallel.For(from, to, index =>

    {

        array[index] = Math.Sqrt(index);

    });

     return array;

}

 

Stay connected with news and updates!

Join our mailing list to receive the latest news and updates from our team.
Don't worry, your information will not be shared.

Subscribe
Close

50% Complete

Two Step

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.