Are Parallel.Invoke and Parallel.ForEach essentially the same thing?
Parallel.ForEach
goes through the list of elements and can perform some task on the elements of the array.
eg.
Parallel.ForEach(val, (array) => Sum(array));
Parallel.Invoke
can invoke many functions in parallel.
eg.
Parallel.Invoke(() => doSum(array),() => doAvg(array),() => doMedian(array));
As from the example above, you can see that they are different in functionality. ForEach
iterates through a List
of elements and performs one task on each element in parallel, while Invoke
can perform many tasks in parallel on a single element.
Parallel.Invoke and Parallel.ForEach (when used to execute Actions) function the same, although yes one specifically wants the collection to be an Array. Consider the following sample:
List<Action> actionsList = new List<Action> { () => Console.WriteLine("0"), () => Console.WriteLine("1"), () => Console.WriteLine("2"), () => Console.WriteLine("3"), () => Console.WriteLine("4"), () => Console.WriteLine("5"), () => Console.WriteLine("6"), () => Console.WriteLine("7"), () => Console.WriteLine("8"), () => Console.WriteLine("9"), }; Parallel.ForEach<Action>(actionsList, ( o => o() )); Console.WriteLine(); Action[] actionsArray = new Action[] { () => Console.WriteLine("0"), () => Console.WriteLine("1"), () => Console.WriteLine("2"), () => Console.WriteLine("3"), () => Console.WriteLine("4"), () => Console.WriteLine("5"), () => Console.WriteLine("6"), () => Console.WriteLine("7"), () => Console.WriteLine("8"), () => Console.WriteLine("9"), }; Parallel.Invoke(actionsArray); Console.ReadKey();
This code produces this output on one Run. It's output is generally in a different order every time.
0 5 1 6 2 7 3 8 4 9
0 1 2 4 5 6 7 8 9 3
I'm trying to find a good way of phrasing it; but they are not the same thing.
The reason is, Invoke works on an Array of Action and ForEach works on a List (specifically an IEnumerable) of Action; Lists are significantly different to Arrays in mechanics although they expose the same sort of basic behaviour.
I can't say what the difference actually entails because I don't know, so please don't accept this an an answer (unless you really want too!) but I hope it jogs someones memory as to the mechanisms.
+1 for a good question too.
Edit; It just occurred to me that there is another answer too; Invoke can work on a dynamic list of Actions; but Foreach can work with a Generic IEnumerable of Actions and gives you the ability to use conditional logic, Action by Action; so you could test a condition before saying Action.Invoke() in each Foreach iteration.