Using a parallel foreach loop to run multiple threads

A while ago, during a work retreat (yes, the company I work for is really that cool), Graham Rook, who is one of my colleagues, showed me a parallel foreach loop. It certainly speeds up processing a great deal. But here's the rub. It makes no sense using a parallel foreach loop if you're dealing with small amounts of data or little tasks. The parallel foreach loop excels when there is bulk processing to do or huge amounts of data to process.

Getting ready

We will start off by looking at where the parallel foreach loop does not perform better than the standard foreach loop. For this, we will create a small list of 500 items and just iterate over the list, writing the items to the console window. ...

Get C# Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.