Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parallel.Invoke() without waiting on execution to finish

Please know that I'm aware that Parallel.Invoke() is meant for task synchronization. My question is this:

Is there a way to call an anonymous method using something like Parallel.Invoke in which the call does NOT wait on the execution to finish?

I thought the whole point of parallel execution (or parallel invokation) is to NOT have to wait for the task to finish. If you want to wait for a piece of code to finish executing, instead of using Parallel.Invoke, why not just call the code directly? I guess I just don't understand the point of Parallel.Invoke. The documentation just says what it does, but doesn't mention any use-cases when this would be more useful than just calling the code directly.

like image 712
Anshul Avatar asked Jan 29 '14 20:01

Anshul


2 Answers

If you want to wait for a piece of code to finish executing, instead of using Parallel.Invoke, why not just call the code directly?

Well normally you'd call Parallel.Invoke with multiple pieces of work. If you execute those pieces of work in series, it'll (probably) take longer than executing them in parallel.

"Execute in parallel" isn't the same as "execute in the background" - you appear to be looking for the latter, but that's not what Parallel.Invoke is about.

If you just want to start tasks, use Task.Run (or Task.Factory.StartNew prior to .NET 4.5). Parallel.Invoke is specifically for executing a bunch of actions in parallel, but then waiting for those parallel actions to complete.

As a concrete example, you can perform a sort by partitioning, then recursively sorting both sides of the pivot in parallel. Doing this will make use of multiple cores, but you would usually still want to wait until that whole sort had completed before you proceed.

like image 181
Jon Skeet Avatar answered Oct 04 '22 18:10

Jon Skeet


Simply wrap your Parallel.Invoke call in a Task if you don't want to wait for completion.

Task.Factory.StartNew( () =>
    {
        Parallel.Invoke( <one or more actions> );
    } );
like image 43
Moho Avatar answered Oct 04 '22 19:10

Moho