Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating through each Enum value needs to be parallelized

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);
}
like image 669
LoneXcoder Avatar asked Mar 06 '26 17:03

LoneXcoder


2 Answers

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.

like image 75
Mike Zboray Avatar answered Mar 09 '26 10:03

Mike Zboray


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.

like image 28
Happy Bird Avatar answered Mar 09 '26 10:03

Happy Bird



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!