So I just cant grasp the concept here. I have a Method that uses the Parallel class with the Foreach method. But the thing I dont understand is, does it create new threads so it can run the function faster?
Let's take this as an example. I do a normal foreach loop.
private static void DoSimpleWork() { foreach (var item in collection) { //DoWork(); } } What that will do is, it will take the first item in the list, assign the method DoWork(); to it and wait until it finishes. Simple, plain and works.
Now.. There are three cases I am curious about If I do this.
Parallel.ForEach(stringList, simpleString => { DoMagic(simpleString); }); Will that split up the Foreach into let's say 4 chunks? So what I think is happening is that it takes the first 4 lines in the list, assigns each string to each "thread" (assuming parallel creates 4 virtual threads) does the work and then starts with the next 4 in that list? If that is wrong please correct me I really want to understand how this works.
And then we have this. Which essentially is the same but with a new parameter
Parallel.ForEach(stringList, new ParallelOptions() { MaxDegreeOfParallelism = 32 }, simpleString => { DoMagic(simpleString); }); What I am curious about is this
new ParallelOptions() { MaxDegreeOfParallelism = 32 } Does that mean it will take the first 32 strings from that list (if there even is that many in the list) and then do the same thing as I was talking about above?
And for the last one.
Task.Factory.StartNew(() => { Parallel.ForEach(stringList, simpleString => { DoMagic(simpleString); }); }); Would that create a new task, assigning each "chunk" to it's own task?