-1

I have 3 foreach function's, writing the list l of type / class Person to Console

            foreach(Person p in l)
            {
                Console.WriteLine(p.first);
                Console.WriteLine(p.last);
            }

            l.ForEach(p =>
            {
                Console.WriteLine(p.first);
                Console.WriteLine(p.last);
            });

            Parallel.ForEach(l, p =>
            {
                Console.WriteLine(p.first);
                Console.WriteLine(p.last);
            });

They are all doing the same except that Parallel is working with threading i guess. What should i use when?

Blobslam
  • 13
  • 4
  • 3
    Multithreading only makes sense when things benefit from said threading. Simple console output doesn't benefit from it. Between the first two it's mostly opinion based – UnholySheep May 19 '20 at 11:36
  • There is no "should" for any of these. First, you have opinions, the first two are favorites among different people, so you will not get **the** answer, you will only get **an** answer. Secondly, it depends on context, parallel code should only be used when you *want* parallelism, in this case it will probably jumble the output so I would stay away from it. In my opinion, you should use the first piece. – Lasse V. Karlsen May 19 '20 at 11:55
  • 2
    I would argue that you should just use `foreach` unless you benefit greatly by parallelism, and avoid `List.Foreach()`. It adds no functional benefit, only mildly different syntax. The problem is it _only_ works on `List`. I've seen code that converts an array to a list _just_ to use `ForEach()`, which is dumb. – D Stanley May 19 '20 at 12:35
  • Why is it dumb converting an array to a list? Isn't that easier to write in the end after converting an array to a list? Instead of for(var i = 0; i < array.length; i++) just the converted array as list .ForEach()? – Blobslam May 19 '20 at 12:52

1 Answers1

0

Here you are using a method that is defined on the List<> class:

l.ForEach(p => { ... });

Internally this uses a for loop to iterate the collection. Use it when you want shorter and more readable code.

A standard foreach provides a bit more control over the loop e.g. breaking out of the loop when a specific condition is met. If want to read more about this just have a look at this article which provides in-depth information about this kind of topic.

Compared to the standard foreach loop, the Parallel.ForEach loop executes in a parallel manner. It uses multiple threads, as you already suggested. Use this when you want to execute multiple processes concurrently. Read more about this here.

Parallel.ForEach(l, p => { ... });
oRole
  • 1,316
  • 1
  • 8
  • 24