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:
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.
An example:
enum Gender{
male,
female
}
Parallel.ForEach((Gender[])Enum.GetValues(typeof(Gender)), gender=>
{
Console.WriteLine(gender.ToString()) // example: code goes here
});
Meaning: For each Gender gender, execute code between { } asynchronously.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With