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.
For the second example that illustrates the power of the parallel foreach
loop, we will use the same list and create a file for each item in the list. The power and benefit of the parallel foreach
loop will be evident in the second example.