I'm new to the Parallel class in .NET. I have this basic code:
List<Action> actions = new List<Action>();
for (int iter = 1; iter <= 5; iter++)
{
actions.Add(() =>
{
// create a local copy of iter, and an action to write it to the console
int theProblem = iter;
Console.WriteLine(theProblem);
});
}
Parallel.Invoke(actions.ToArray());
/*
Output:
6
6
6
6
6
*/
I would expect this to print 1..5 in some random order, but instead it prints out the value of iter after the loop ends.
Why is this? At what point are the actions actually created, and the line int theProblem = iter;
executed?
I found a TON of information online about Parallel.For and Parallel.ForEach (not so much for Parallel.Invoke), but nothing explaining specifically what goes on in a very basic case like this one.
What modifications do I need to make to have the code above print 1..5 (in some random order)?
Thanks a lot!
EDIT:
This question has been marked as a duplicate, but I don't think it is:
All except one of the responses in the other question refer to sigle-threaded code, this is multi-threaded.
None of the responses refers to Parallel.Invoke (or to any other method in the Parallel class for that matter).
My code sample already implements the solutions proposed in the other question (create a copy of the variable inside the loop), and yet it's not working.
So, clearly not a dupe.
EDIT 2:
Turns out that this is actually a dupe under the hood. The gist of it is to create the local copy of the variable inside the loop but outside the lambda (duh!) and then everything works just as expected.
Thanks everyone!