NDepend

Improve your .NET code quality with NDepend

How to collect return values from Parallel.ForEach?

How to collect return values from Parallel.ForEach

Today I took 10 minutes to answer the 9 years old stackoverflow’s question: How do I collect return values from Parallel.ForEach? I though the improved solution deserved a quick blog post since it hasen’t been mentioned.

The accepted answer proposes to use a concurrent collection to store the result:

Concurrent collection is necessarily expensive since internally it relies on threading lock. There is 89 mentions of “lock” in the source code of ConcurrentBag<T>.

However in the particular case where the size of the collection is known upfront – and this is often the case in practice – an array of the size of the inputs can be used to store outputs. Now each loop receives its very own index, both to access the input and store the output. There is no risk of concurrent access collision here:

There is a bonus with this solution: outputs are stored with the same order as inputs, while the order is random when using a concurrent collection.

This is a trick we use for more than a decade in the NDepend code base, even before TPL (Task Parallel Library) was released. The rule of thumb is to avoid concurrent access when possible, and with a bit of astute this is often possible.

My dad being an early programmer in the 70's, I have been fortunate to switch from playing with Lego, to program my own micro-games, when I was still a kid. Since then I never stop programming.

I graduated in Mathematics and Software engineering. After a decade of C++ programming and consultancy, I got interested in the brand new .NET platform in 2002. I had the chance to write the best-seller book (in French) on .NET and C#, published by O'Reilly and also did manage some academic and professional courses on the platform and C#.

Over my consulting years I built an expertise about the architecture, the evolution and the maintenance challenges of large & complex real-world applications. It seemed like the spaghetti & entangled monolithic legacy concerned every sufficiently large team. As a consequence, I got interested in static code analysis and started the project NDepend in 2004.

Nowadays NDepend is a full-fledged Independent Software Vendor (ISV). With more than 12.000 client companies, including many of the Fortune 500 ones, NDepend offers deeper insight and full control on their application to a wide range of professional users around the world.

I live with my wife and our twin kids Léna and Paul in the beautiful island of Mauritius in the Indian Ocean.