Embracing Parallel LINQ

It’s easy as a developer to forget that .net 3.5+ comes with some pretty helpful tools; one of the ones that elude most people is the use of Parallel LINQ.

Parallel LINQ allows you to better utilise multicore processors on the machines hosting the application. It increases time efficiency massively in long algorithms when the loop contents are mutually exclusive to one another. It’s understandable to assume that it would be a lot of work to try and make use of the multiple cores, but thankfully Microsoft has made it incredibly easy.

Take the following code for example:

 

It doesn’t matter whether the Enumerable is processed in order, or whether multiple cores (and threads) can process each member independently and only continue once all the threads have completed. To rework the above code using Parallel LINQ, it is just a case of re-writing one line:

 

And that’s it, it’s that simple!

I think with the way devices are going now (even most current phones have multiple processors!) that writing code designed to utilise all the cores is something that most developers should welcome and embrace as something that will help deliver faster results to the user.