Parallel programming - made too easy in .Net 4?

by Danielvg 25. November 2009 00:01

I am doing a test project at DTU under the Edison Project, where I basically have to make a program that is able to simulate the power consumption of multiple electric vehicles with different driving patterns, batteries and user profiles. After having made a prototype that ran on one thread I started to talk with a colleague at work on improving performance and getting it to run on multiple cores, he quickly suggested the new Parallel library which ships with .Net 4 Beta 2. I was really surprised at how easy it was to implement, all it took was 1 line of code to make the prototype utilize all cores in the system!

Going from:

private void CalculateTick(IEnumerable<ICar> cars)
{
    tickNumber++;
    tickDate = tickDate.AddSeconds(1); 
    foreach(var car in cars)
    {
        car.CalculateTick(tickDate);
    }
}

to:
private void CalculateTick(IEnumerable<ICar> cars)
{
    tickNumber++;
    tickDate = tickDate.AddSeconds(1);
    Parallel.ForEach(cars, (car) =>
        {
            car.CalculateTick(tickDate);
        });
}

did the trick of making the program run 3 times faster (using a test system with 4 cores)

I have a feeling that it is just too easy, you do not really get a chance to think about the effects this could have on the elements within the loops. But with that said.. I Love it!, and I will definitely take advantage of multiple cores more often!

If you want to read more about Parallel Extensions, which even includes parallel linq, a good place to start is here