What are the advantages of Parallel.Foreach in C#?

Asked

Viewed 664 times

7

Working with C# I saw that we have the option to work with parallel.ForEach(). What is the advantage of working with her and not the foreach?

2 answers

10

Her name pretty much gives away everything that’s being asked. This way the iteration in a sequence of items is evaluated in parallel, as far as possible, and in some scenarios this can take advantage of the full potential of the hardware being used. With parallelization the total process can end faster. It can be applied to any object that implements the interface IEnumerable (see more).

Parallelization will not always bring gains. There is a certain risk of making an algorithm that does not work as well in parallel. It is always necessary to make a test whether it compensates or not.

There are problems that cannot be broken into parts to parallelize. The most typical example is when a result depends on the previous results.

Parallelization only compensates where there are multiple processors.

Documentation.

5

Depends on the application.

If you have a lot of data to be processed and the order does not import the best is parallel processing (Parallel.Foreach()), otherwise the best is foreach or other loop repetition.

Parallel.Foreach(), what it does is take your collection and split it into threads and run what has to be done! basically that’s it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.