Parallel to .Invoke (), without waiting for execution to complete

Please know that I know that Parallel.Invoke () is intended for task synchronization. My question is this:

Is there a way to invoke an anonymous method using something like Parallel.Invoke, in which the call does NOT wait for the execution to complete?

I thought that the whole point of parallel execution (or parallel call) should not wait for the task to complete. If you want to wait for the code snippet to finish, instead of using Parallel.Invoke, why not just call the code directly? I guess I just don’t understand what Parallel is. The documentation just says what it does, but does not mention any use cases where it would be more useful than just calling the code directly.

+7
multithreading c # parallel-processing task-parallel-library
source share
3 answers

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

Good thing you would call Parallel.Invoke few jobs. If you complete these parts of the work in sequence, it will (probably) take longer than doing them in parallel.

Running in parallel is not the same as running in the background - you seem to be looking for the latter, but that is not what Parallel.Invoke about.

If you just want to run tasks, use Task.Run (or Task.Factory.StartNew before .NET 4.5). Parallel.Invoke designed to perform parallel parallel operations, but then waits for these parallel actions to complete.

As a specific example, you can sort, partition, then recursively sort both sides of the axis in parallel. This will use multiple cores, but as a rule, you still want to wait until all of this is complete before you begin.

+9
source share

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

 Task.Factory.StartNew( () => { Parallel.Invoke( <one or more actions> ); } ); 
+5
source share

Are you looking for something like this?

 async Task ParallelInvokeAsync(Action[] actions) { var tasks = actions.Select(a => Task.Run(a)); await Task.WhenAll(tasks); } 

Background execution:

 ParallelInvokeAsync(actions); MessageBox.Show("I'm working"); 

Running a background with a lock, very similar to Parallel.Invoke :

 ParallelInvokeAsync(actions).Wait(); MessageBox.Show("I'm dome working"); 
+3
source share

All Articles