C#’s Parallel.Invoke is [Insert Hyperbole Here]

Reading Time: 2 minutes

Freeside VTIt’s simple – we can’t make processors go any faster. But we can add more cores.
The OS can schedule different processes to different cores but to take full advantage of the potential we need to be writing applications that run on multiple cores.
Unsurprisingly there’s a lot of investment in making this easier for programmers – to the point that it’s now easier than falling off a log…

Parallel.Invoke(
    () =>
    {
        if (!GetSomethingFromTheDb(out something))
            something = MakeUpSomethingFromSomewhere();
    },
    () =>
    {
        complexResult = SomeComplexOperation();
    },
    () =>
    {
        someObjectGraph = ReadAndParseSomeFile(fileName);
    });
SomeReallyComplexThing(something, complexResult, someObjectGraph);

The individual actions will be run in parallel, or to be more precise may be run in parallel. The task scheduler takes care of whether or not to actually run them in parallel and the degree of parallelism.

When we arrive at SomeReallyComplexThing all the previous tasks will have been done.

That’s ace. It’s a lot easier than messing about with threads.

Even before the Parallel library was around it wasn’t actually difficult, but you needed some lateral thinking…

Task[] tasks = new Task[] {
    Task.Factory.StartNew(()=>
    {
        if (!GetSomethingFromTheDb(out something))
            something = MakeUpSomethingFromSomewhere();
        }),
    Task.Factory.StartNew(()=>
    {
        complexResult = SomeComplexOperation();
    }),
    Task.Factory.StartNew(()=>
    {
        someObjectGraph = ReadAndParseSomeFile(fileName);
    })
};
Task.WaitAll(tasks);
SomeReallyComplexThing(something, complexResult, someObjectGraph);

Ok, I admit, I’m simplifying. You still need to understand the basic problems of concurrent programming but the mechanics of writing code that can take advantage of parallelism are now trivial.