Iterating through each Enum value needs to be parallelized

.net, c#, enums, task-parallel-library

Solution

You've closed over a loop variable. Each Task you are starting has a reference to the same closed over variable, which is changing as you iterate the collection.

You need something like this:

public static void TasteAll<Mode>(Action<Mode> Make)
{
        foreach (Mode mode in Enum.GetValues(typeof(Mode)))
        {
            Mode localMode = mode;
            Task.Factory.StartNew(() => Make(localMode) );
            //Make(mode); //<-- Works Fine with normal call
        }
    Console.ReadLine();
}

With C# 5, loop variables are now semantically inside of the loop block, so this is unnecessary. See Eric Lippert's blog for additional discussion.

Problem

What am I doing wrong in the parallel call? ``` static void Main(string[] args) { TasteAll<HotCupOf>(TurnCoffeeVenMachineOn); } public static void TasteAll<Mode>(Action<Mode> Make) { foreach (Mode mode in Enum.GetValues(typeof(Mode))) { Task.Factory.StartNew(() => Make(mode) ); //Make(mode); //<-- Works Fine with normal call } Console.ReadLine(); } enum HotCupOf { Black, Latte, Cappuccino, Mocha, Americano, Espresso, Chocolate, Tea } public static void TurnCoffeeVenMachineOn(HotCupOf SelectedDrink) { Console.WriteLine(SelectedDrink); } ```

Original source