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);
}
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:
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.