Parallel Programming In C# To Leverage Multicore Processor

Performance issues

We often find it very difficult to get a solution for performance issues faced in real world applications.

We use multiple loops to iterate huge amounts of data for processing (e.g. for, foreach, Linq ) queries for the iteration and this results in bad performing code.

Here is the solution

Microsoft® .NET Framework 4 introduces Parallel Programming model, which utilizes all the CPU cores and runs your Application code in parallel on all the cores, so that you get the fastest computation of your program written in C#.

The normal ( for, foreach, Linq ) iterates in the sequential manner, which means, even if your program is running on a multicore processor, only one core of the processor is used to compute your program.

Hence, basically you are not getting any benefit of using a multi core processor.

Below are some examples (with comparisons), which may help you to get all the benefits of running an Application on a multi core processor machine and get the fastest results.

for vs Parallel.For

When we run the code, given below, we can see the difference.

code

Normal “for loop“ prints the results sequentially (It means, only single core of CPU is processing the loop) and taking time to complete.

Whereas “Parallel.For” printing results non sequentially, which shows the parallel processing of the loop over the multiple cores and producing output much faster than the normal for loop.

output

“Parallel.For” takes first input, which is the starting index and then the maximum index (Excluding).

foreach vs Parallel.Foreach

code

Output

Normal “foreach loop“ prints the results sequentially.
Whereas “Parallel.Foreach” prints the results non sequentially.

output

Linq vs PLinq

Given below is the sample code to compare the outputs of the two approaches.

code

array.ForEach gives the results sequentially.

array.AsParallel() produces the output in parallel.

output

Making a small change in the way of writing the code can make a huge difference.

Up Next
    Ebook Download
    View all
    Learn
    View all