c# – What are Parallel.For and Parallel.ForEach loops?

Question:

I saw the use of Parallel.For and Parallel.ForEach in some places, I know they are loops , but I don't understand how and when to use them and I have my doubts.

What are Parallel.For and Parallel.ForEach loops ?

When should we use them?

Is there any difference between them?

Answer:

Imagine you have a directory on your computer with 8 music files in FLAC format. Excellent format by the way, clean audio.

Now imagine that you want to convert these files from FLAC to MP3 (not that good) because your cd-player (nor mine) recognize the FLAC format. You will create your own code to convert audio files:

First, let's get a list of the audios using a method I just invented.

FlacAudio[] audioFiles = FlacHelper.ReadFromDirectory("caminhoDoDiretorio");

Okay, we have a list with the 8 music files.

Now let's convert them:

List<Mp3Audio> mp3Files = new List<Mp3Audio>();

foreach (FlacAudio file in audioFiles)
{
   Mp3Audio mp3 = FlacHelper.ConvertToMp3(file);
   mp3Files.Add(mp3);
}

// Salvar os arquivos convertidos no diretório destino...

Here, in this foreach iterator only one thread is used for each of the 8 files, so while the first one is being converted, the other 7 are impatiently waiting. But hey, you have an Intel Core I7 processor with 8 threads available, so why wait?

Let's rewrite code so that all this processing power is enjoyed:

List<Mp3Audio> mp3Files = new List<Mp3Audio>();

Parallel.ForEach(audioFiles, file =>
{
   Mp3Audio mp3 = FlacHelper.ConvertToMp3(file);
   mp3Files.Add(mp3);
});

Okay, in this code, Parallel foreach discovers and uses all available threads of your processor so that the action, which in this case is converting audio files, is executed in parallel, so each thread will convert a file at the same time.

Considering it would take 1 minute for each file, the default foreach would take a total of 8 minutes, while a Parallel.ForEach would take 1 minute considering 8 files in the directory and a processor with 8 threads.

Parallel.For works exactly as you imagine:

List<Mp3Audio> mp3Files = new List<Mp3Audio>();

Parallel.For(0, files.Length - 1,
index => { 
            Mp3Audio mp3 = FlacHelper.ConvertToMp3(audioFiles[index]);
            mp3Files.Add(mp3);
         }); // Index é o número da iteração atual, que neste caso parte de zero e é incrementada a cada iteração.

When to use:

For operations that depend on processing (CPU-Bound) and that can be performed in parallel when there is more than one instance of an item to be processed, similarly to our playlist.

Disclaimer :

Using Parallel.ForEach in simple operations/iterations that don't use a lot of resources is not guaranteed to be faster than a standard foreach . In fact, the cost of allocating threads the way Parallel does can cause an overhead that slows down your code, so the "weight" of the operation being executed inside foreach is what will dictate whether or not it's worth it. in the parallel way.

Scroll to Top